SQL WINDOW FUNC 当没有唯一分区
SQL WINDOW FUNC when no unique partition
我有这个 table:
日期
ID
Product_A_Count
Product_B_Count
1
一个
1
2
2
一个
1
2
3
一个
2
1
4
一个
1
2
我想将其转换为:
Start_Date
End_Date
ID
Product_A_Count
Product_B_Count
1
2
一个
1
2
3
3
一个
2
1
4
4
一个
1
2
有没有办法只使用 SQL 来做到这一点?我一直在尝试 row_number 和滞后,但 none 看起来是正确的(因为按 ID、Product_A_Count 和 Product_B_Count 组合的分区不是唯一的)。
非常感谢所有建议!!
这是一种间隙岛问题。在这种情况下,行号的差异可能是最简单的解决方案:
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);
例如,如果日期都是规则间隔的,可能会有更简单的解决方案。
我有这个 table:
日期 | ID | Product_A_Count | Product_B_Count |
---|---|---|---|
1 | 一个 | 1 | 2 |
2 | 一个 | 1 | 2 |
3 | 一个 | 2 | 1 |
4 | 一个 | 1 | 2 |
我想将其转换为:
Start_Date | End_Date | ID | Product_A_Count | Product_B_Count |
---|---|---|---|---|
1 | 2 | 一个 | 1 | 2 |
3 | 3 | 一个 | 2 | 1 |
4 | 4 | 一个 | 1 | 2 |
有没有办法只使用 SQL 来做到这一点?我一直在尝试 row_number 和滞后,但 none 看起来是正确的(因为按 ID、Product_A_Count 和 Product_B_Count 组合的分区不是唯一的)。
非常感谢所有建议!!
这是一种间隙岛问题。在这种情况下,行号的差异可能是最简单的解决方案:
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);
例如,如果日期都是规则间隔的,可能会有更简单的解决方案。