sql 按序列分组,岛屿问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 按序列分组,岛屿问题相关的知识,希望对你有一定的参考价值。

;WITH YourTable AS
(
SELECT 1 AS N, 'A' AS C UNION ALL
SELECT 2 AS N, 'A' AS C UNION ALL
SELECT 3 AS N, 'A' AS C UNION ALL
SELECT 4 AS N, 'B' AS C UNION ALL
SELECT 5 AS N, 'B' AS C UNION ALL
SELECT 6 AS N, 'B' AS C UNION ALL
SELECT 7 AS N, 'A' AS C UNION ALL
SELECT 8 AS N, 'A' AS C
),
     T
     AS (SELECT N,
                C,
                DENSE_RANK() OVER (ORDER BY N) - 
                DENSE_RANK() OVER (PARTITION BY C ORDER BY N) AS Grp
         FROM   YourTable)
SELECT COUNT(*),
       C
FROM   T
GROUP  BY C,
          Grp 
ORDER BY MIN(N)

----------------------------------------------------------------------------

以上是关于sql 按序列分组,岛屿问题的主要内容,如果未能解决你的问题,请参考以下文章

按时间序列分组的 SQL 查询

差距和岛屿 - 如何按 ID 对每组连续行求和

如何使用熊猫按 10 分钟对时间序列进行分组

按 ID 分组并完成时间序列 Pandas [重复]

按序列号和天间隔分组的平均温度

如何将字符串序列化为 JSON 并按其中一个值分组?