1

要求是基于 10 秒的时间间隔对表的记录进行分组。给定表

 Id      DateTime            Rank
 1     2011-09-27 18:36:15      1
 2     2011-09-27 18:36:15      1
 3     2011-09-27 18:36:19      1
 4     2011-09-27 18:36:23      1
 5     2011-09-27 18:36:26      1
 6     2011-09-27 18:36:30      1
 7     2011-09-27 18:36:32      1
 8     2011-09-27 18:36:14      2
 9     2011-09-27 18:36:16      2
 10    2011-09-27 18:36:35      2

组应该是这样的

 Id      DateTime            Rank    GroupRank
 1     2011-09-27 18:36:15      1         1
 2     2011-09-27 18:36:15      1         1
 3     2011-09-27 18:36:19      1         1
 4     2011-09-27 18:36:23      1         1
 5     2011-09-27 18:36:26      1         2
 6     2011-09-27 18:36:30      1         2
 7     2011-09-27 18:36:32      1         2
 8     2011-09-27 18:36:14      2         3
 9     2011-09-27 18:36:16      2         3
 10    2011-09-27 18:36:35      2         4

对于 Rank 1,最短时间是 18:36:15,因此 18:36:15 到 18:36:24 之间的所有记录都应该在一个组中,依此类推。

我希望 GroupRank 在同一张表中。所以它会是带有 dense_Rank() Over 子句的东西。谁能帮我用 SQL 编写查询。

4

1 回答 1

0

您需要分两步执行此操作,第一步是将每条记录分成 10 秒组,方法是获取每个等级的最短时间的秒数差异,将其除以 10,然后将其向下舍入到最接近的整数.

SELECT  *,
        SecondGroup = FLOOR(DATEDIFF(SECOND, 
                                    MIN([DateTime]) OVER(PARTITION BY [Rank]), 
                                    [DateTime]) / 10.0)
FROM    #T;

这使:

Id  DateTime                    Rank    SecondGroup
---------------------------------------------------
1   2011-09-27 18:36:15.000     1       0
2   2011-09-27 18:36:15.000     1       0
3   2011-09-27 18:36:19.000     1       0
4   2011-09-27 18:36:23.000     1       0
5   2011-09-27 18:36:26.000     1       1
6   2011-09-27 18:36:30.000     1       1
7   2011-09-27 18:36:32.000     1       1
8   2011-09-27 18:36:14.000     2       0
9   2011-09-27 18:36:16.000     2       0
10  2011-09-27 18:36:35.000     2       2

然后您可以通过and进行DENSE_RANK订购:RankSecondGroup

SELECT  Id, [DateTime], [Rank],
        GroupRank = DENSE_RANK() OVER(ORDER BY [Rank], SecondGroup)
FROM    (   SELECT  *,
                    SecondGroup = FLOOR(DATEDIFF(SECOND, 
                                                MIN([DateTime]) OVER(PARTITION BY [Rank]), 
                                                [DateTime]) / 10.0)
            FROM    #T
        ) AS t;

这给出了您想要的输出。

样本数据

CREATE TABLE #T (Id INT, [DateTime] DATETIME, [Rank] INT);

INSERT #T (Id, [DateTime], [Rank])
VALUES
    (1, '2011-09-27 18:36:15', 1),
    (2, '2011-09-27 18:36:15', 1),
    (3, '2011-09-27 18:36:19', 1),
    (4, '2011-09-27 18:36:23', 1),
    (5, '2011-09-27 18:36:26', 1),
    (6, '2011-09-27 18:36:30', 1),
    (7, '2011-09-27 18:36:32', 1),
    (8, '2011-09-27 18:36:14', 2),
    (9, '2011-09-27 18:36:16', 2),
    (10, '2011-09-27 18:36:35', 2);
于 2016-07-19T10:13:28.320 回答