聚合时间范围MSSQL

时间:2018-03-23 10:28:18

标签: sql-server datetime aggregation window-functions

给出下表显示计算机上的登录时间,如果有人可以帮我写一个MS SQL查询来提供表2中的聚合时间表,我将不胜感激:

表1(数据):

Usrkey  Username    DateTime_From           DateTime_To

1       Fox         2012-01-01 08:00    2012-01-01 08:15
1       Fox         2012-01-01 08:20    2012-01-01 08:25
2       Foxi        2012-01-01 09:30    2012-01-01 09:40
2       Foxi        2012-01-01 10:20    2012-01-01 10:25
1       Fox         2012-01-01 10:30    2012-01-01 10:35
1       Fox         2012-01-01 11:00    2012-01-01 11:40
2       Foxi        2012-01-01 12:50    2012-01-01 13:25
2       Foxi        2012-01-02 08:20    2012-01-02 08:25
2       Foxi        2012-01-02 09:20    2012-01-02 09:25
1       Fox         2012-01-02 11:30    2012-01-02 11:45
1       Fox         2012-01-02 12:50    2012-01-02 13:00
1       Fox         2012-01-02 13:20    2012-01-02 14:00

表2(期望的结果):

Usrkey  Username    RangeFrom           RangeTo
1       Fox         2012-01-01 08:00    2012-01-01 08:25
2       Foxi        2012-01-01 09:30    2012-01-01 10:25
1       Fox         2012-01-02 10:30    2012-01-01 11:40
2       Foxi        2012-01-01 12:50    2012-01-02 09:25
1       Fox         2012-01-02 11:30    2012-01-02 14:00

非常感谢您的支持!

霍里亚

1 个答案:

答案 0 :(得分:1)

OP没有对他们尝试的内容作出回应,但我仍然建议他们这样做。这是一种使用ROW_NUMBER()的不同方法,但是,如果您使用LEAD / LAG发布您尝试的内容,那么我们也可以向您显示您在那里出错了。

反正:

WITH VTE AS(
    SELECT Usrkey,
           Username,
           CONVERT(datetime2(0),DateTime_From) AS DateTime_From,
           CONVERT(datetime2(0),DateTime_To) AS DateTime_To
    FROM (VALUES (1,'Fox ','2012-01-01T08:00:00','2012-01-01T08:15:00'),
                 (1,'Fox ','2012-01-01T08:20:00','2012-01-01T08:25:00'),
                 (2,'Foxi','2012-01-01T09:30:00','2012-01-01T09:40:00'),
                 (2,'Foxi','2012-01-01T10:20:00','2012-01-01T10:25:00'),
                 (1,'Fox ','2012-01-01T10:30:00','2012-01-01T10:35:00'),
                 (1,'Fox ','2012-01-01T11:00:00','2012-01-01T11:40:00'),
                 (2,'Foxi','2012-01-01T12:50:00','2012-01-01T13:25:00'),
                 (2,'Foxi','2012-01-02T08:20:00','2012-01-02T08:25:00'),
                 (2,'Foxi','2012-01-02T09:20:00','2012-01-02T09:25:00'),
                 (1,'Fox ','2012-01-02T11:30:00','2012-01-02T11:45:00'),
                 (1,'Fox ','2012-01-02T12:50:00','2012-01-02T13:00:00'),
                 (1,'Fox ','2012-01-02T13:20:00','2012-01-02T14:00:00')) V(Usrkey,Username,DateTime_From,DateTime_To)),
Grps AS(
    SELECT Usrkey,
           Username,
           DateTime_From,
           DateTime_To,
           ROW_NUMBER() OVER (ORDER BY DateTime_From ASC) -
           ROW_NUMBER() OVER (PARTITION BY Usrkey ORDER BY DateTime_From ASC) AS Grp
    FROM VTE)
SELECT Usrkey, Username,
       MIN(DateTime_From) AS DateTime_From,
       MAX(DateTime_To) AS DateTime_To
FROM Grps
GROUP BY Usrkey, Username, Grp
ORDER BY DateTime_From ASC;