Select 一行基于 sql 中的月份和年份

Select one row based on Month and Year in sql

我有一个 table 这样的:

 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  |

我想根据 InMonth=Month 和 InYear=Year 显示结果 data/row。如果 InMonth 与 Month 不同,InYear 与 Year 不同,则获取前一个 data/row。像这样:

 ID |     Cost     | Month |  Year  | InMonth | InYear |
1081|     13500    |   9   |  2016  |    10   |  2016  |
1229|      7800    |   5   |  2016  |    10   |  2016  |
1312|     99000    |   5   |  2016  |    10   |  2016  |

我试过这个:

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

您正在使用 Postgres。我建议 distinct on:

select distinct on (id) t.*
from t
where year < inyear or
      (year = inyear and month <= inmonth)
order by id, year desc, month desc;

对不起,我只能post。我使用此代码:

select "ID", "Cost", "Month", "Year", "rn"
 from ( select "ID", "Cost", "Month", "Year",
  row_number() over(partition by "ID" order by "Year" desc, "Month" desc)
  as RN
from price_history where "InMonth">="Month" and "InYear">="Year" 
) X
where RN=1