查询中的 TSQL Order/Sequence 个组
TSQL Order/Sequence groups in a query
我有以下数据...
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 服务器)
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;
与 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
我有以下数据...
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 服务器)
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;
与 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