I have a table like
SR No | Name | Amount 1 | Amount 2 | Year |
---|---|---|---|---|
1 | Crop1 | 1000 | 3000 | 2023 |
2 | Crop2 | 2000 | 1000 | 2023 |
3 | Crop3 | 5000 | 2500 | 2022 |
4 | Crop4 | 1500 | 3500 | 2022 |
5 | Crop5 | 3500 | 4500 | 2021 |
6 | Crop6 | 9500 | 4000 | 2021 |
Now, I want Result like
Year | Year Sum | Previous year Sum |
---|---|---|
2023 | 3000 | 6000 |
2022 | 6000 | 8500 |
2021 | 8500 | 0 |
Explanation - Year 2023 -> Year Sum = total of Amount 1 of year 2023 Year 2023 -> Previous Year Sum = total of amount 2 of year 2022 Year 2022 -> Year Sum = total of Amount 2 of year 2022(Previous year total of year 2023 row) Year 2022 -> Previous Year Sum = total of Amount 2 of year 2021 Year 2021 -> Year Sum = total of Amount 2 of year 2021(Previous year total of year 2022 row). Year 2021 -> Previous Year Sum = total of Amount 2 of year 2020.
I have tried using case when conditions but not getting proper result,
How to get result like this.
2
Answers
You can use a cte and window functions:
db-fiddle
When the "Year Sum" is the total of "Amount 1" (always), you can do:
output:
First get the totals, then use
LAG()
to move the totals to the previous year.see: DBFIDDLE