A B C D
1pm a 1 1
2pm a 2 2
3pm b 1 1
4pm b 2 2
5pm a 3 1
6pm a 4 2
当我做row_number() over (partition by B order by A) as C .
时,得到C列。如何得到D列?
答案 0 :(得分:1)
您需要为“相邻”值分配一个组。一种简单的方法是行号的区别:
select a, b,
row_number() over (partition by b, (seqnum_a - seqnum_ab) order by a) as d
from (select t.*,
row_number() over (order by a) as seqnum_a,
row_number() over (partition by b order by a) as seqnum_ab
from t
) t;
行号的不同是某些类型的“离岛”问题(基本上是您要的问题)的一种解决方案。为什么行之有效的解释有些棘手。我发现,如果有人看到了子查询的结果,他们通常会明白为什么差异标识相邻行。