SQL: Gaps and Island Problem - Date not consecutive causing rank inaccurate

霸气de小男生 提交于 2019-12-24 06:22:58

问题


This is a follow up on the other question I asked.

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
   Q1 2020    A          A1          *1* I want 1 not 2 here because it's not consecutive (we don't have Q3 & Q4 2019)
   Q2 2020    A          A1          *2* I want 2 not 3 here because it reset in Q1 2020.

Below query works if the dates are consecutive. How would I adjust the query to get what I'm looking for? I tried adding a new column that is 1 row lag, and tried to check if the quarter value in the new column is essentially the true previous 1 quarter (if yes, use the counter, if not, use "1" to restart). But it doesn't reset the following records. Then I am not sure what to do.

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;

回答1:


You need to fix your data model! In any case, this is solved by enumerating the quarters.

select quarter, customer, segment,
       row_number() over (partition by customer, segment, q_seqnum - seqnum_cs order by q_seqnum) as counter
from (select t.*,
             row_number() over (partition by customer, segment order by q_seqnum) as seqnum_cs
      from (select t.*,
                   cast(right(quarter, 4) as int) * 4 + cast(substring(quarter, 2, 1) as int) as q_seqnum
            from t
           ) t
     ) t
order by customer, q_seqnum;


来源:https://stackoverflow.com/questions/59431244/sql-gaps-and-island-problem-date-not-consecutive-causing-rank-inaccurate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!