SQL Server:按连续分组

时间:2017-10-27 13:33:24

标签: sql sql-server-2008 group-by

我有这张桌子:

CREATE TABLE yourtable 
(
    HevEvenementID INT,
    HjvNumeSequJour INT,
    HteTypeEvenID INT
);

INSERT INTO yourtable 
VALUES (12074, 1, 66), (12074, 2, 66), (12074, 3, 5),
       (12074, 4, 7), (12074, 5, 17), (12074, 6, 17),
       (12074, 7, 17), (12074, 8, 17), (12074, 9, 17), (12074, 10, 5)

我需要按连续HteTypeEvenID进行分组。现在我这样做:

SELECT
    HevEvenementID,
    MAX(HjvNumeSequJour) AS HjvNumeSequJour,
    HteTypeEvenID
FROM
    (SELECT
         HevEvenementID,
         HjvNumeSequJour,
         HteTypeEvenID
     FROM
         yourtable y) AS s 
GROUP BY
    HevEvenementID, HteTypeEvenID
ORDER BY
    HevEvenementID,HjvNumeSequJour, HteTypeEvenID

返回:

HevEvenementID  HjvNumeSequJour HteTypeEvenID
---------------------------------------------
12074            2              66
12074            4               7
12074            9              17
12074           10               5

我需要按连续HteTypeEvenID进行分组才能获得此结果:

HevEvenementID  HjvNumeSequJour HteTypeEvenID
----------------------------------------------
12074           2               66
12074           3                5
12074           4                7
12074           9               17
12074           10               5

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

在SQL Server中,您可以使用聚合和行号差异来执行此操作:

select HevEvenementID, HteTypeEvenID,
       max(HjvNumeSequJour)
from (select t.*,
             row_number() over (partition by HevEvenementID order by HjvNumeSequJour) as seqnum_1,
             row_number() over (partition by HevEvenementID, HteTypeEvenID order by HjvNumeSequJour) as seqnum_2
      from yourtable t
     ) t
group by HevEvenementID, HteTypeEvenID, (seqnum_1 - seqnum_2)
order by max(HjvNumeSequJour);

我认为了解其工作原理的最佳方法是盯着子查询的结果。您将看到两个值之间的差异如何定义相邻值的组。