重复值的密集排名
Dense rank for duplicated values
id val dense_rank
1 11 => 1
2 11 1
3 22 2
4 33 3
5 33 3
6 11 4
sql想要什么样的dense_rank?
用lag()
算出前一个值是多少,然后一个累加和:
select t.*,
count(*) filter (where prev_val is null or prev_val <> val) over (order by id) as dense_rank
from (select t.*, lag(val) over (order by id) as prev_val
from t
) t;
Here 是一个 db<>fiddle.
id val dense_rank
1 11 => 1
2 11 1
3 22 2
4 33 3
5 33 3
6 11 4
sql想要什么样的dense_rank?
用lag()
算出前一个值是多少,然后一个累加和:
select t.*,
count(*) filter (where prev_val is null or prev_val <> val) over (order by id) as dense_rank
from (select t.*, lag(val) over (order by id) as prev_val
from t
) t;
Here 是一个 db<>fiddle.