Actual:
| Year | Quarter | Value | prev_quarter_val | Name | Date |
|---|---|---|---|---|---|
| FY 2021 | Q1 | 2456 | NULL | XYZ | 01-01-2020 |
| FY 2021 | Q2 | NULL | 2456 | XYZ | 01-01-2020 |
| FY 2021 | Q3 | 2345 | 2456 | XYZ | 01-01-2020 |
| FY 2021 | Q3 | NULL | 2345 (which is wrong) | XYZ | 01-01-2020 |
| FY 2021 | Q4 | 3456 | 2345 | XYZ | 01-01-2020 |
Expected:
| Year | Quarter | Value | prev_quarter_val | Name | Date |
|---|---|---|---|---|---|
| FY 2021 | Q1 | 2456 | NULL | XYZ | 01-01-2020 |
| FY 2021 | Q2 | NULL | 2456 | XYZ | 01-01-2020 |
| FY 2021 | Q3 | 2345 | 2456 | XYZ | 01-01-2020 |
| FY 2021 | Q3 | NULL | 2456 | XYZ | 01-01-2020 |
| FY 2021 | Q4 | 3456 | 2345 | XYZ | 01-01-2020 |
In the above tables, I have the columns year, quarter, value, name,prev_quarter_val and date. I have to fill the value column with values from previous quarter. If the previous quarter's value is NULL, fetch the value from the latest quarter and year where it is not NULL.
What I have tried:
SELECT year,quarter,name,date,value,prev_quarter_val
FROM (SELECT year,quarter,name,date,value, LAG(value,1)
OVER (PARTITION BY date, name ORDER BY year,quarter) AS prev_quarter_val
FROM table t)
The problem with my code is it takes the value from the same quarter if the value is present twice
How can I fix the query such that it takes from previous quarter even if its present twice?
Edit: It has to take value from previous year and it is not restricted to year constraints.