I am attempting to find percentage change per each month per company.
Table
Year Mon company_id Revenue
2018 2018-06-01 42 2000
2018 2018-07-01 42 3000
2019 2019-06-01 42 4000
2019 2019-07-01 42 9000
I attempted this and failed.
select *, lag(Revenue) over(partition by company_id order by Year) from table
working to get the bellow result ( the table has multiple company_ids)
Year Mon company_id Revenue percentage change
2018 2018-06-01 42 2000
2018 2018-07-01 42 3000
2019 2019-06-01 42 4000 100
2019 2019-07-01 42 9000 200
2
Answers
Woof!
You need to tickle out the month so that you can partition by it:
This assumes that the
date
stored inmon
only serves to identify the month, and that the "year" part of it (which is different fromyear
) is irrelevant.You may use a window function to get exact the row with offset one year in the past.
This will work even if you have a missing data for some year (you will not match a two or more years old revenue).
Unfortunately this does not work for me in
14.6
withLAG
(not sure if per design), so I’m usingMAX
.Example