假设下面有一张桌子。我想要一个计数器来计算客户(有很多)在细分A中的次数。如果客户在两个季度之间跳到另一个细分,则当客户跳回到细分时计数器将重置答:我确信有很多方法可以做到这一点,但是我只是想不通。请帮助。谢谢!
Quarter Segment Customer **Counter**
Q1 2018 A A1 1
Q2 2018 A A1 2
Q3 2018 A A1 3
Q4 2018 B A1 1
Q1 2019 B A1 2
Q2 2019 A A1 1
Q3 2019 A A1 2
select quarter, customer, segment,
row_number() over (partition by customer, segment, seqnum - seqnum_cs order by right(quarter, 4), left(quarter, 2)) as counter
from (select t.*,
row_number() over (partition by customer order by right(quarter, 4), left(quarter, 2)) as seqnum,
row_number() over (partition by customer, segment order by right(quarter, 4), left(quarter, 2)) as seqnum_cs
from t
) t
order by customer, seqnum;