【问题标题】:SQL: Gaps and Island Problem - Date not consecutive causing rank inaccurateSQL:差距和孤岛问题 - 日期不连续导致排名不准确
【发布时间】:2020-04-13 07:42:32
【问题描述】:

这是我对the other question 的跟进。

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.

如果日期是连续的,则以下查询有效。我将如何调整查询以获得我正在寻找的内容?我尝试添加一个滞后 1 行的新列,并尝试检查新列中的季度值是否本质上是真实的前 1 个季度(如果是,使用计数器,如果不是,使用“1”重新启动)。但它不会重置以下记录。那我不知道该怎么办了。

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;

【问题讨论】:

    标签: sql database amazon-redshift window-functions gaps-and-islands


    【解决方案1】:

    您需要修复数据模型!无论如何,这是通过枚举四分之一来解决的。

    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;
    

    【讨论】:

    • 这确实有效!但是你能解释一下吗!在我的真实数据中,这是一个有效的场景,因为这是一个派生表(不是实际表),如果客户不满足特定条件,则它不在任何细分市场中。此外,在我的真实数据中,季度不是字符串而是日期。因此,如果我们将季度视为日期(因此实际上不需要进行子字符串转换),还可以这样做吗? @戈登林诺夫
    • @user12562215 。 . .这只是生成季度的序列号(年乘以四加上季度)。然后,减去一个递增的序列会得到一个常数值——对于相邻的数字。
    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多