我试图达到以下目标"排名"给定由列ID和CODE组成的原始数据集的结果。
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代码在&#34之后得到相同的等级值;中断之间的#34;
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
是否有可能实现第一个(示例)表中所示的结果,当id:1-2-3形成的组与id形成的组之间存在分隔时,A代码会改变等级: 9-10没有使用光标?
由于
答案 0 :(得分:3)
您想要查找值序列并为其指定排名。你可以通过行数方法的不同来做到这一点。以下内容为每个分组指定了不同的编号:
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
排序,但这需要额外的窗口功能:
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;
答案 1 :(得分:1)
如果current与上一行相同,则为SUM。适用于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
请在How to make row numbering with ordering, partitioning and grouping
查看类似问题