【问题标题】:Select one row based on Month and Year in sql在sql中根据月份和年份选择一行
【发布时间】:2017-10-06 09:36:30
【问题描述】:

我有一张这样的桌子:

 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

【问题讨论】:

  • "InMonth"&gt;="Month" and "InYear"&gt;="Year" 移动到where 子句不是更好吗.. 你甚至不需要row_number
  • 为什么 9 出现在您要求的结果中,而 2 却没有?
  • 谢谢大家,我已经解决了问题

标签: sql postgresql odoo-8


【解决方案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;

【讨论】:

  • 谢谢,我下个问题试试
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 2018-03-02
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多