我在SQL Server中有这种数据
Person StartDate EndDate Value
-----------------------------------------------------------------
38523 2013-01-10 22:00:00.000 2013-01-10 22:59:00.000 0.064
38523 2013-01-10 23:00:00.000 2013-01-10 23:59:00.000 0.065
38523 2013-01-12 00:00:00.000 2013-01-12 00:59:00.000 0.068
38523 2013-01-12 01:00:00.000 2013-01-12 01:59:00.000 0.069
38523 2013-01-12 02:00:00.000 2013-01-12 02:59:00.000 0.069
38523 2013-01-12 03:00:00.000 2013-01-12 03:59:00.000 0.069
38523 2013-01-31 23:00:00.000 2013-01-31 23:59:00.000 0.061
38523 2013-02-01 00:00:00.000 2013-02-01 00:59:00.000 0.064
我需要以这样一种方式进行分组,即每个月应将连续值组合在一起。 如果在上一个结束日期和下一个开始日期之间存在超过1分钟的间隔,则应将其拆分为单独的组。
预期结果:
Person StartDate EndDate Sum(Value)
----------------------------------------------------------------------
38523 2013-01-10 22:00:00.000 2013-01-10 23:59:00.000 0.129
38523 2013-01-12 00:00:00.000 2013-01-12 03:59:00.000 0.275
38523 2013-01-31 23:00:00.000 2013-01-31 23:59:00.000 0.061 (even though continuity exists, month was end hence separate record)
38523 2013-02-01 00:00:00.000 2013-02-01 00:59:00.000 0.064
任何帮助表示感谢。
答案 0 :(得分:0)
SELECT
CAST(DATEPART(YEAR, DateCreated) as varchar(10)) + '/'
+ CAST(DATEPART(MONTH, DateCreated) as varchar(10))
FROM [Reporting].[dbo].[Hmis_Forms]
GROUP BY
CAST(DATEPART(YEAR, DateCreated) as varchar(10)) + '/'
+ CAST(DATEPART(MONTH, DateCreated) as varchar(10))
答案 1 :(得分:0)
根据您的数据和预期结果,以下查询可以帮助您:
SELECT
Person,
MIN(StartDate) as StartDate,
MAX(EndDate) as EndDate,
SUM(Value)
FROM table
GROUP BY
Person,
CAST(StartDate as date)
答案 2 :(得分:0)
我有类似的东西,也许这可以帮到你:
CREATE TABLE #Test2
(
Person int,
StartDate datetime,
EndDate datetime,
Value numeric (12, 3),
NextDate datetime
);
INSERT INTO #Test2(Person, StartDate, EndDate, Value, NextDate)
SELECT
Person,
StartDate,
EndDate,
Value,
(SELECT TOP 1 StartDate FROM Test WHERE StartDate > t.EndDate ORDER BY StartDate, EndDate)
FROM Test t
SELECT
MAX(StartDate) ,
MAX(EndDate) ,
SUM(Value)
FROM #Test2
GROUP BY
DATEDIFF(MINUTE, NextDate, EndDate)
ORDER BY
MAX(StartDate) ,
MAX(EndDate)
DROP TABLE #Test2
我做的是用新列创建临时表,保留下一个开始日期值。然后,我根据开始和结束日期的减法对值进行分组,以分钟为单位计算。
除了总和之外,我得到的结果与你的结果相同。