説明するのが少し難しく、私の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
各レコードの[値]の合計を計算したいと思います。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
これは意味がありますか?