稍微難以解釋,我的SQL Server不是最好的,但任何事情都可以在這裏完成。當前記錄和下一條記錄之間的列總和
首先,創建一些表:
CREATE TABLE [dbo].[Quarterly](
[QuarterDate] [datetime] NOT NULL,
[SomeText] [nvarchar](50) NULL,
CONSTRAINT [PK_Quarterly] PRIMARY KEY CLUSTERED
(
[QuarterDate] ASC
)
GO
CREATE TABLE [dbo].[TmpDegreeDays](
[Date] [datetime] NOT NULL,
[Value] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_TmpDegreeDays] PRIMARY KEY CLUSTERED
(
[Date] ASC
)
GO
然後插入一些數據:
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009CF100000000 AS DateTime), N'Blah')
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009D4B00000000 AS DateTime), N'Fools')
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009DA600000000 AS DateTime), N'Later')
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009E0400000000 AS DateTime), N'Something')
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009E5E00000000 AS DateTime), N'New year')
INSERT [dbo].[Quarterly] ([QuarterDate], [SomeText]) VALUES (CAST(0x00009EC300000000 AS DateTime), N'In april')
然後從2010-01-01
插入日期範圍至(含)2012-03-10
成表TmpDegreeDays
最後:
我想計算對於當前QuarterDate
與Quarterly
結果集中下一條記錄之間的Quarterly
表中的每條記錄,請使用[值]的和SUM。
喜歡的東西:最終輸出的
DECLARE @startDate datetime, @endDate datetime
SET @startDate = '2010-01-01'
SET @endDate = '2010-12-31'
SELECT q.QuarterDate, q.SomeText, CustomSum =
(SELECT SUM(CAST([Value] AS float))
FROM TmpDegreeDays
WHERE [date] >= q.QuarterDate AND *Current QuarterDate* < *Some query here to get next row QuarterDate*)
FROM Quarterly q
WHERE q.QuarterDate BETWEEN @startDate AND @endDate
例子我要找:
2010-01-01 Sum of [Value] between 2010-01-01 and 2010-03-31
2010-04-01 Sum of [Value] between 2010-04-01 and 2010-06-30
2010-07-01 Sum of [Value] between 2010-07-01 and 2010-09-31
2010-10-03 Sum of [Value] between 2010-10-03 and 2010-10-03
這是否有道理?
首先:爲什麼你讓你的INSERT如此複雜?爲什麼不使用'INSERT INTO [dbo]。[Quarterly]([QuarterDate],[SomeText])VALUES('20100101',N'Blah')'等等? **很多**比你的奇怪的鑄造更容易.....另外:如果你有一個度數值的表 - **爲什麼**是'值'列'VARCHAR(50)'?不應該像'DECIMAL(10,4)'或類似的東西? Varchar在這裏完全沒有意義..... – 2012-04-17 21:08:15
馬克 - 它不是我的代碼:-)我只是把它。相信我,它會做得更好 – 2012-04-17 21:17:35
但是'SUM'甚至不會**在'VARCHAR'列工作** - 你一定要改變一些東西..... – 2012-04-17 21:18:34