【发布时间】: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
【问题讨论】:
-
将
"InMonth">="Month" and "InYear">="Year"移动到where 子句不是更好吗.. 你甚至不需要row_number -
为什么 9 出现在您要求的结果中,而 2 却没有?
-
谢谢大家,我已经解决了问题
标签: sql postgresql odoo-8