I have a table like this:
ID | Cost | Month | Year | InMonth | InYear |
--------------------------------------------------------
1081| 13000 | 5 | 2017 | 10 | 2016 |
1081| 13500 | 9 | 2016 | 10 | 2016 |
1081| 21000 | 2 | 2016 | 10 | 2016 |
1229| 6500 | 7 | 2017 | 10 | 2016 |
1229| 7800 | 5 | 2016 | 10 | 2016 |
1312| 110000 | 8 | 2017 | 10 | 2016 |
1312| 120000 | 5 | 2017 | 10 | 2016 |
1312| 99000 | 5 | 2016 | 10 | 2016 |
I want to show result data/row based on InMonth=Month and InYear=Year. If InMonth not same like Month and InYear not same like Year, get previous data/row. Like this:
ID | Cost | Month | Year | InMonth | InYear |
1081| 13500 | 9 | 2016 | 10 | 2016 |
1229| 7800 | 5 | 2016 | 10 | 2016 |
1312| 99000 | 5 | 2016 | 10 | 2016 |
I have tried this:
select "ID", "Cost", "Month", "Year"
from ( select "ID", "Cost", "Month", "Year",
case when "InMonth">="Month" and "InYear">="Year"
then row_number() over(partition by "ID" order by "Year" desc, "Month" desc)
else 0
end as RN
from price_history
) X
where RN<>0
SQL Fiddle: http://sqlfiddle.com/#!15/7b8b6f/1/0