Slightly difficult to explain and my SQL Server is not the best but anything will do here.
First, create some tables:
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
Then insert some data:
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')
Then insert date ranges from 2010-01-01 to (including) 2012-03-10 into table TmpDegreeDays
Finally:
I want to calculate the SUM of [Value] in TmpDegreeDays for each record in the Quarterly table between the current QuarterDate and the next record in the Quarterly resultset.
Something like:
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
Example of final output I am looking for:
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
Does this make sense?
You could try something like this – using a CTE (available in SQL Server 2005 and newer) to find the dates for each quarter and then summing up the degree values:
The strange function to determine the
QuarterEndDateis rooted in the fact that theDATETIMEhas a precision of 3.33ms in SQL Server. Thus, the last date for a given month is the last day of that month, and the time is23:59:59.997(not .999). Therefore, I need to add three months to the quarter’s start date, and then subtract 3 milliseconds from that start date of the next quarter to get the last millisecond of this quarter in question.Update: OK, in order to get the start and end date for a quarter from the table, you need two nested CTE’s in order to determine the “end date of the next quarter minus 3 milliseconds” for the end of the quarter – something like this: