2

我在 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

任何帮助表示赞赏。

4

3 回答 3

0

仅根据您的数据和预期结果,以下查询可能对您有所帮助:

SELECT 
    Person, 
    MIN(StartDate) as StartDate, 
    MAX(EndDate) as EndDate, 
    SUM(Value)
FROM table
GROUP BY 
    Person, 
    CAST(StartDate as date)
于 2013-03-20T07:13:42.077 回答
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))
于 2013-03-20T06:43:45.400 回答
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

我要做的是创建带有新列的临时表,以保留下一个起始日期值。然后,我根据开始和结束日期的减法对值进行分组,以分钟为单位。

除了总和之外,我得到的结果与您的结果相同。

于 2013-03-20T08:36:26.897 回答