Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL List previous sales of dates in the current month

enter image description here

enter image description here

On the sql side, as seen in the table below, I want to subtract the sale of the day before today’s date and have it printed in a separate column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

example; Subtract the sale on 2022-04-17 from the sale on 2022-04-18 and write it in the side column.

subtract the sales from the previous day until you find the last date in the table in a loop.

>Solution :

You can try to use LEAD window function with CASE WHEN expression

SELECT *,
    CASE WHEN LEAD(n_Sales) OVER(PARTITION BY CustomerId,ProductId ORDER BY Date DESC) IS NULL 
        THEN Sales ELSE 
        Sales - LEAD(n_Sales) OVER(PARTITION BY CustomerId,ProductId ORDER BY Date DESC) 
    END
FROM T
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading