如果下一行状态相同,则提供相同排名的分区 [英] Partitioning that gives the same rank if the next row status is the same
本文介绍了如果下一行状态相同,则提供相同排名的分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
寻找解决分区问题的帮助,在此问题中,如果下一行的状态与前一行相同,我会尝试给予相同的排名。数据集如下所示:
log_id user status date
1 1 a 2020-01-01
2 1 b 2020-01-03
3 1 a 2020-01-18
4 1 a 2020-02-03
5 1 c 2020-02-05
6 2 a 2020-01-05
7 2 c 2020-01-10
8 2 b 2020-01-12
9 2 a 2020-01-21
10 2 a 2020-01-23
11 2 a 2020-01-28
12 2 b 2020-01-29
我尝试通过以下方式按用户对行进行分区:
select
t.*,
rank() over (partition by t.user order by t.date) as rank_order
from table t
这将使我获得按用户划分的日志ID的简单排名:
log_id user status date rank_order
1 1 a 2020-01-01 1
2 1 b 2020-01-03 2
3 1 a 2020-01-18 3
4 1 a 2020-02-03 4
5 1 c 2020-02-05 5
6 2 a 2020-01-05 1
7 2 c 2020-01-10 2
8 2 b 2020-01-12 3
9 2 a 2020-01-21 4
10 2 a 2020-01-23 5
11 2 a 2020-01-28 6
12 2 b 2020-01-29 7
但如果下一行具有相同的状态,我会给出相同的排名。如下所示:
log_id user status date desired_rank_order
1 1 a 2020-01-01 1
2 1 b 2020-01-03 2
3 1 a 2020-01-18 3
4 1 a 2020-02-03 3
5 1 c 2020-02-05 4
6 2 a 2020-01-05 1
7 2 c 2020-01-10 2
8 2 b 2020-01-12 3
9 2 a 2020-01-21 4
10 2 a 2020-01-23 4
11 2 a 2020-01-28 4
12 2 b 2020-01-29 5
推荐答案
您可以执行以下操作:
select *,
sum(inc) over(partition by user order by date) as rank_order
from (
select *,
case when lag(status) over(partition by user order by date) = status
then 0 else 1 end as inc
from t
) x
这篇关于如果下一行状态相同,则提供相同排名的分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文