简体   繁体   中英

snowflake sql: sum for each day between two dates

I hope someone can help. Suppose I have this table

id actual_date target_date qty
1 2022-01-01 2022-01-01 2
2 2022-01-02 2022-01-01 1
3 2022-01-03 2022-01-01 3
4 2022-01-03 2022-01-02 1
5 2022-01-03 2022-01-03 2

what i would like to calculate is the qty that has to be processed on each date.

Eg on the target date 2022-01-01 the quota qty is 6 (2+1+3).

On the 2.1.2022 i would also have to add the qtys that havent been processed on the day before, which means id 2 because the actual date is 2022-01-02 (so after the target date) and id 3. The quota qty for the 2022-01-02 is then 1+3+1.

And for the 2022-01-03 is 6 = 2+1+3, because id 3 has an actual date on 2022-01-02 (it wasnt processed neither on 01-01 nor on 01-02 and id 4 wasnt processed on 01-02.

Here's what the desired output would look like:

target_date qty_qouta
2022-01-01 6
2022-01-02 4
2022-01-03 6

在此处输入图像描述

Hopefully this gets you started... recommend testing heaps more edge cases, the business rules don't quite feel right to me -> as you don't seem to show when actual>target. But hope this helps.

WITH CTE AS( SELECT 1 ID, '2022-01-01'::DATE ACTUAL_DATE,'2022-01-01'::DATE TARGET_DATE, 2 QTY
UNION ALL SELECT 2 ID, '2022-01-02'::DATE ACTUAL_DATE,'2022-01-01'::DATE TARGET_DATE, 1 QTY
UNION ALL SELECT 3 ID, '2022-01-03'::DATE ACTUAL_DATE,'2022-01-01'::DATE TARGET_DATE, 3 QTY
UNION ALL SELECT 4 ID, '2022-01-03'::DATE ACTUAL_DATE,'2022-01-02'::DATE TARGET_DATE, 1 QTY
UNION ALL SELECT 5 ID, '2022-01-03'::DATE ACTUAL_DATE,'2022-01-03'::DATE TARGET_DATE, 2 QTY
)
,CTE2 AS(SELECT 
     ACTUAL_DATE D
 ,   SUM(QTY) ACTUAL_QTY
  FROM CTE GROUP BY 1)
,CTE3 AS(SELECT 
     TARGET_DATE D
 ,   SUM(QTY) TARGET_QTY
  FROM CTE GROUP BY 1)
  SELECT 
     D DATE
    ,ACTUAL_QTY
    ,TARGET_QTY
    ,TARGET_QTY-ACTUAL_QTY DELTA
    ,ZEROIFNULL(LAG(DELTA)OVER(PARTITION BY 1 ORDER BY D))GHOST
    ,GREATEST(TARGET_QTY,DELTA+GHOST,ACTUAL_QTY)VOLIA
   FROM 
        CTE2 FULL OUTER JOIN CTE3 USING(D);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM