SQL 排名分组变化
SQL rank grouping variation
给定由列 ID 和 CODE 组成的原始数据集,我正在尝试实现以下 "rank" 结果。
id code rank
1 A 1
2 A 1
3 A 1
4 B 2
5 B 2
6 C 3
7 C 3
8 C 3
9 A 4
10 A 4
在 CODE 列上使用 RANK_DENSE 指令我得到以下结果(A 代码在行之间的 "the break" 之后也获得相同的排名值)
id code rank
1 A 1
2 A 1
3 A 1
4 B 2
5 B 2
6 C 3
7 C 3
8 C 3
9 A 1
10 A 1
是否可以实现第一个(示例)所示的结果table,当id: 1-2-3 和id: 9-10 组成的那个不使用游标?
谢谢
您想查找值序列并给它们排序。您可以使用不同的行号方法来执行此操作。以下为每个分组分配不同的编号:
select o.*, dense_rank() over (order by grp, code)
from (select o.*,
(row_number() over (order by id) -
row_number() over (partition by code order by id)
) as grp
from original o
) o;
如果您希望按与原始数据相同的顺序进行赋值,则可以按 id
排序,但这需要额外的 window 函数:
select o.*, dense_rank() over (order by minid) as therank
from (select o.*, min(id) over (partition by grp, code) as minid
from (select o.*,
(row_number() over (order by id) -
row_number() over (partition by code order by id)
) as grp
from original o
) o
) o;
如果当前行与上一行相同则求和。适用于 SQL Server 2012。
WITH CTE AS (
SELECT id, code,
CASE Code WHEN LAG(CODE) OVER (ORDER BY id) THEN 0 ELSE 1 END AS Diff
FROM Table1)
SELECT id, code, SUM(Diff) OVER (ORDER BY id) FROM CTE
另请参阅
中的类似问题
给定由列 ID 和 CODE 组成的原始数据集,我正在尝试实现以下 "rank" 结果。
id code rank
1 A 1
2 A 1
3 A 1
4 B 2
5 B 2
6 C 3
7 C 3
8 C 3
9 A 4
10 A 4
在 CODE 列上使用 RANK_DENSE 指令我得到以下结果(A 代码在行之间的 "the break" 之后也获得相同的排名值)
id code rank
1 A 1
2 A 1
3 A 1
4 B 2
5 B 2
6 C 3
7 C 3
8 C 3
9 A 1
10 A 1
是否可以实现第一个(示例)所示的结果table,当id: 1-2-3 和id: 9-10 组成的那个不使用游标?
谢谢
您想查找值序列并给它们排序。您可以使用不同的行号方法来执行此操作。以下为每个分组分配不同的编号:
select o.*, dense_rank() over (order by grp, code)
from (select o.*,
(row_number() over (order by id) -
row_number() over (partition by code order by id)
) as grp
from original o
) o;
如果您希望按与原始数据相同的顺序进行赋值,则可以按 id
排序,但这需要额外的 window 函数:
select o.*, dense_rank() over (order by minid) as therank
from (select o.*, min(id) over (partition by grp, code) as minid
from (select o.*,
(row_number() over (order by id) -
row_number() over (partition by code order by id)
) as grp
from original o
) o
) o;
如果当前行与上一行相同则求和。适用于 SQL Server 2012。
WITH CTE AS (
SELECT id, code,
CASE Code WHEN LAG(CODE) OVER (ORDER BY id) THEN 0 ELSE 1 END AS Diff
FROM Table1)
SELECT id, code, SUM(Diff) OVER (ORDER BY id) FROM CTE
另请参阅