有点难以解释,我的 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
最后:
我想为结果集中当前记录和下一条记录之间的表中TmpDegreeDays
的每条记录计算 [Value] 的总和。Quarterly
QuarterDate
Quarterly
就像是:
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
这有意义吗?