DBMS I am using is Teradata.
I have a table called Sales, with columns:
Store, Item, DT, and Volume
This is a daily sales table, where Store and Item are numbers, and DT is a date.
Now, it could be the case that if a store/item combo did not have any sales for a certain date, that it could have no entry in the table, or its entry has a 0 as the value for volume. It is imperative that I consider both cases.
I would like to calculate the max consecutive days with no sales for a store/item combo, where the date range is between ‘2023-12-31’ and ‘2024-03-30’
This is what I have come up with, but it unfortunately does not consider many cases:
SELECT
sq.STORE,
sq.ITEM,
MAX(sq.Consec_No_Sales_Days) AS Max_Consec_No_Sales_Days
FROM (
SELECT
STORE,
ITEM,
DT - LAG(DT)
OVER(ORDER BY STORE,ITEM,DT) AS Consec_No_Sales_Days
FROM
SALES
WHERE
SALES.VOLUME > 0
AND DT BETWEEN '2023-12-31' AND '2024-03-30'
GROUP BY
STORE,
ITEM,
DT
) sq
WHERE
sq.Consec_No_Sales_Days > 0
GROUP BY
sq.STORE,
sq.ITEM