请建议使用良好的SQL查询来查找库存差异的开始和结束日期
想象我在下表中的数据。
Sample_table
transaction_date stock
2018-12-01 10
2018-12-02 10
2018-12-03 20
2018-12-04 20
2018-12-05 20
2018-12-06 20
2018-12-07 20
2018-12-08 10
2018-12-09 10
2018-12-10 30
预期结果应为
Start_date end_date stock
2018-12-01 2018-12-02 10
2018-12-03 2018-12-07 20
2018-12-08 2018-12-09 10
2018-12-10 null 30
答案 0 :(得分:5)
这是差距和孤岛的问题。您可以为此使用row_numer和group by。
select t.stock, min(transaction_date), max(transaction_date)
from (
select row_number() over (order by transaction_date) -
row_number() over (partition by stock order by transaction_date) grp,
transaction_date,
stock
from data
) t
group by t.grp, t.stock
在下面的DBFIDDLE DEMO中,我也解决了最后一组的null
值,但是查找连续行的主要思想是基于上述查询。
您可以检查this以获得此解决方案的说明。
答案 1 :(得分:1)
您可以使用row_number()
select stock,min(transaction_date) as start_date,
case when min(transaction_date)=max(transaction_date) then null else max(transaction_date) end as end_date
from
(
select *,row_number() over(order by transaction_date)-
row_number() over(partition by stock order by transaction_date) as rn
from t1
)A group by stock,rn
答案 2 :(得分:0)
尝试将GROUP BY
与MIN
和MAX
结合使用:
SELECT
stock,
MIN(transaction_date) Start_date,
CASE WHEN COUNT(*)>1 THEN MAX(transaction_date) END end_date
FROM Sample_table
GROUP BY stock
ORDER BY stock
答案 3 :(得分:0)
您可以尝试使用LEAD,LAG功能,如下所示:
quiz