根据sql中的月份和年份选择一行

根据sql中的月份和年份选择一行,sql,postgresql,odoo-8,Sql,Postgresql,Odoo 8,我有一张这样的桌子: ID | Cost | Month | Year | InMonth | InYear | -------------------------------------------------------- 1081| 13000 | 5 | 2017 | 10 | 2016 | 1081| 13500 | 9 | 2016 | 10 | 2016 | 1081| 2

我有一张这样的桌子:

 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显示结果数据/行。如果InMonth与Month不相同,InYear与Year不相同,则获取以前的数据/行。像这样:

 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 FIDLE:

您正在使用Postgres。我建议:


您正在使用Postgres。我建议:


对不起,我可以发邮件。我使用以下代码:

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

对不起,我可以发邮件。我使用以下代码:

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

将InMonth>=月和InYear>=年移到where子句不是更好吗。。你甚至不需要行号,那么为什么9出现在你的必选结果中而2不出现呢?谢谢大家,我已经解决了这个问题,将InMonth>=Month和InYear>=Year移到where子句不是更好吗。。你甚至不需要行号,那么为什么9出现在你的必选结果中而2不出现?谢谢大家,我已经解决了这个问题谢谢,我会在下一个问题中尝试谢谢,我会在下一个问题中尝试