我有以下数据。
a_id state date
1 A 7/5/19
1 A 7/6/19
1 M 7/7/19
1 M 7/8/19
1 A 7/9/19
1 A 7/10/19
1 A 7/11/19
1 M 7/12/19
我想使用SQL为每个组按顺序到达它们。
例如,A有2个组,因为它们没有以相同的顺序到达。对于M同样 请参见下面的预期输出。
a_id state date result col
1 A 7/5/19 1
1 A 7/6/19 1
1 M 7/7/19 2
1 M 7/8/19 2
1 A 7/9/19 3
1 A 7/10/19 3
1 A 7/11/19 3
1 M 7/12/19 4
答案 0 :(得分:0)
这是一个孤岛问题。您可以使用lag()
和累计金额:
select t.*,
sum(case when state = prev_state then 0 else 1 end) over (partition by a_od order by date) as result
from (select t.*,
lag(state) over (partition by a_id order by date) as prev_state
from t
) t;