SQL 按顺序分组和组的顺序 ID
Posted
技术标签:
【中文标题】SQL 按顺序分组和组的顺序 ID【英文标题】:SQL Grouping in sequence & Sequential ID for group 【发布时间】:2021-12-17 07:56:48 【问题描述】:我有以下 SQL 数据库,想按顺序对它们进行分组,并为每个组分配 ID。
Time | Line | Colour |
---|---|---|
2021-11-02 3:00:00PM | 1 | Black |
2021-11-02 3:00:01PM | 1 | White |
2021-11-02 3:00:02PM | 1 | Red |
2021-11-02 3:00:04PM | 1 | Red |
2021-11-02 3:00:05PM | 1 | Black |
2021-11-02 3:00:06PM | 1 | Black |
2021-11-02 3:00:00PM | 2 | Black |
2021-11-02 3:00:01PM | 2 | Black |
2021-11-02 3:00:02PM | 2 | White |
2021-11-02 3:00:03PM | 2 | White |
2021-11-02 3:00:03PM | 2 | White |
2021-11-02 3:00:03PM | 2 | Black |
2021-11-02 3:00:03PM | 2 | Black |
我正在寻找的结果是
Time | Line | Colour | Qty | Group ID |
---|---|---|---|---|
2021-11-02 3:00:00PM | 1 | Black | 1 | 1 |
2021-11-02 3:00:01PM | 1 | White | 1 | 2 |
2021-11-02 3:00:02PM | 1 | Red | 2 | 3 |
2021-11-02 3:00:04PM | 1 | Red | 2 | 3 |
2021-11-02 3:00:05PM | 1 | Black | 2 | 4 |
2021-11-02 3:00:06PM | 1 | Black | 2 | 4 |
2021-11-02 3:00:00PM | 2 | Black | 2 | 1 |
2021-11-02 3:00:01PM | 2 | Black | 2 | 1 |
2021-11-02 3:00:02PM | 2 | White | 3 | 2 |
2021-11-02 3:00:02PM | 2 | White | 3 | 2 |
2021-11-02 3:00:03PM | 2 | White | 3 | 2 |
2021-11-02 3:00:04PM | 2 | Black | 2 | 3 |
2021-11-02 3:00:05PM | 2 | Black | 2 | 3 |
数量基本上是连续一行中相同颜色的#。
组ID是按行换色的顺序ID。
我只是想不通,因为它需要在“时间”列和“行”列中是连续的,并且无法聚合。
【问题讨论】:
提问时,您需要提供minimal reproducible example: (1) DDL 和样本数据填充,即 CREATE 表加上 INSERT T-SQL 语句。 (2) 你需要做什么,即逻辑和你的代码尝试在 T-SQL 中实现它。 (3) 期望的输出,基于上述#1 中的样本数据。 (4) 您的 SQL Server 版本 (SELECT @@version;)。 【参考方案1】:你可以这样做:
SELECT * , COUNT(*) OVER (PARTITION BY Line, groupId) Qty
FROM (
SELECT *
, rank() OVER (PARTITION BY Line ORDER BY Insertdate)
- rank() OVER (PARTITION BY Line, colour ORDER BY Insertdate) AS GroupId
FROM tablename
) t ORDER BY line, Insertdate
db小提琴here
【讨论】:
以上是关于SQL 按顺序分组和组的顺序 ID的主要内容,如果未能解决你的问题,请参考以下文章