稍微难以解释,我的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
这有意义吗?
答案 0 :(得分:1)
您可以尝试这样的方法 - 使用CTE(在SQL Server 2005 和更新版本中提供)查找每个季度的日期,然后总结度数值:
;WITH QuarterlyDates AS
(
SELECT
QuarterDate,
QuarterEndDate = DATEADD(MILLISECOND, -3, DATEADD(MONTH, 3, QuarterDate))
FROM [dbo].[Quarterly]
)
SELECT
qd.QuarterDate, qd.QuarterEndDate,
DegreeSum = (SELECT SUM(DegreeValue)
FROM [dbo].[TmpDegreeDays]
WHERE [Date] BETWEEN qd.QuarterDate AND qd.QuarterEndDate)
FROM
QuarterlyDates qd
确定QuarterEndDate
的奇怪函数的根源在于DATETIME
在SQL Server中的精度为3.33ms。因此,给定月份的最后日期是该月的最后一天,时间是23:59:59.997
(不是.999)。因此,我需要在该季度的开始日期增加三个月,然后从下一季度的开始日期减去3毫秒,以获得本季度的最后一毫秒。
更新:好的,为了从表中获取四分之一的开始和结束日期,您需要两个嵌套的CTE才能确定“下一个季度的结束日期减去3毫秒” “在本季度末 - 这样的事情:
;WITH QuarterStarts AS
(
SELECT
QuarterDate,
QNumber = ROW_NUMBER() OVER(ORDER BY QuarterDate) -- ordering number
FROM [dbo].[Quarterly]
),
Quarters AS
(
SELECT
QuarterStartDate = q1.QuarterDate,
QuarterEndDate = DATEADD(MILLISECOND, -3, q2.QuarterDate)
FROM
QuarterStarts q1
INNER JOIN
QuarterStarts q2 ON q2.QNumber = q1.QNumber + 1
)
SELECT
q.QuarterDate, q.QuarterEndDate,
DegreeSum = (SELECT SUM(DegreeValue)
FROM [dbo].[TmpDegreeDays]
WHERE [Date] BETWEEN q.QuarterDate AND q.QuarterEndDate)
FROM
Quarters q