在sql中根据Month和Year选择一行

时间:2017-10-06 09:36:30

标签: sql postgresql odoo-8

我有一张这样的表:

 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小提琴:http://sqlfiddle.com/#!15/7b8b6f/1/0

2 个答案:

答案 0 :(得分:1)

您使用的是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;

答案 1 :(得分: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