【问题标题】:SQL WINDOW FUNC when no unique partition没有唯一分区时的 SQL WINDOW FUNC
【发布时间】:2021-08-04 21:41:47
【问题描述】:

我有这张桌子:

Date ID Product_A_Count Product_B_Count
1 A 1 2
2 A 1 2
3 A 2 1
4 A 1 2

我想把它转换成:

Start_Date End_Date ID Product_A_Count Product_B_Count
1 2 A 1 2
3 3 A 2 1
4 4 A 1 2

有没有办法只使用 SQL 来做到这一点?我一直在尝试 row_number 和 lag 但没有一个看起来正确(因为按 ID、Product_A_Count 和 Product_B_Count 组合的分区不是唯一的)。

非常感谢所有建议!

【问题讨论】:

    标签: sql window-functions


    【解决方案1】:

    这是一种孤岛问题。在这种情况下,行号的差异可能是最简单的解决方案:

    select id, product_a_count, product_b_count, min(date), max(date)
    from (select t.*,
                 row_number() over (partition by id order by date) as seqnum,
                 row_number() over (partition by id, product_a_count, product_b_count order by date) as seqnum_2
          from t
         ) t
    group by id, product_a_count, product_b_count, (seqnum - seqnum_2);
    

    例如,如果日期都是规则间隔的,则可能会有更简单的解决方案。

    【讨论】:

    • 太棒了!这解决了我的问题!我肯定会阅读更多关于这种技术的信息。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多