查询中的 TSQL 顺序/序列组
Posted
技术标签:
【中文标题】查询中的 TSQL 顺序/序列组【英文标题】:TSQL Order/Sequence groups in a query 【发布时间】:2021-12-26 09:43:05 【问题描述】:我有以下数据...
uid | groupid |
---|---|
1 | 0 |
2 | 0 |
3 | 1 |
4 | 1 |
5 | 1 |
6 | 1 |
7 | 0 |
8 | 0 |
9 | 2 |
10 | 2 |
11 | 2 |
我想对组进行唯一排序,以便获得....
uid | groupid | newGroupId |
---|---|---|
1 | 0 | 0 |
2 | 0 | 0 |
3 | 1 | 1 |
4 | 1 | 1 |
5 | 1 | 1 |
6 | 1 | 1 |
7 | 0 | 2 |
8 | 0 | 2 |
9 | 2 | 3 |
10 | 2 | 3 |
11 | 2 | 3 |
谁能帮我在 SQL (SQL Server) 中做到这一点
【问题讨论】:
uniquely order the groups
是什么意思?
【参考方案1】:
with cte as
(
select * from (values
(1 , 0),
(2 , 0),
(3 , 1),
(4 , 1),
(5 , 1),
(6 , 1),
(7 , 0),
(8 , 0),
(9 , 2),
(10 , 2),
(11 , 2))
t([uid], [groupid])
),
cte2 as
(
select
[uid], [groupid],
newGroupId =
row_number() over(order by [uid])
-
row_number() over(partition by [groupid] order by [uid])
from
cte
)
select
[uid], [groupid],
newGroupId = dense_rank() over(order by newGroupId) - 1
from
cte2;
【讨论】:
【参考方案2】:与 Vadium 略有不同的方法,但可以考虑另一种选择:
;WITH CTE_MAIN AS
(
select * from (values
(1 , 0),
(2 , 0),
(3 , 1),
(4 , 1),
(5 , 1),
(6 , 1),
(7 , 0),
(8 , 0),
(9 , 2),
(10 , 2),
(11 , 2))
t([uid], [groupid])
),
CTE_2 AS
(
SELECT uid, groupid, LAG(groupid,1,-1) OVER(ORDER BY uid) LastGroupID
FROM CTE_MAIN
)
SELECT uid, groupid, SUM(CASE WHEN GroupID <> LastGroupID THEN 1 ELSE 0 END) OVER(ORDER BY uid) - 1 NewGroup
FROM CTE_2
【讨论】:
以上是关于查询中的 TSQL 顺序/序列组的主要内容,如果未能解决你的问题,请参考以下文章