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

How to calculate week over week changes in SQL?

I have a data table that has 3 columns: Week, Type and units. I want to calculate the week over week changes in units for each Type, and the result table will be like this:

Week         Type   Units   Change
2020-12-01    A      10      null
2020-12-01    B      15      null
2020-12-01    C      20      null
2020-12-01    D      18      null
2020-12-08    A      20       10
2020-12-08    B      15       0
2020-12-08    C      25       5
2020-12-08    D      15      -3
... 

I tried to use the lag function but failed maybe because I’m confused what to use in partition by and order by. Can someone please help me?

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

>Solution :

Since you want the previous "Units" for the same "Type", the partition is on the "Type".

SELECT *
, Units - LAG(Units) OVER (PARTITION BY [Type] ORDER BY [Week]) AS Change
FROM data_table
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