选择一行,每个id在sql查询中查找odoo

时间:2017-10-05 09:12:23

标签: sql postgresql greatest-n-per-group odoo-8

我有一张这样的表:

 ID |     Cost     | Month |  Year  |
-------------------------------------
1081|     13000    |   5   |  2017  |
1081|     13500    |   9   |  2016  |
1081|     21000    |   2   |  2016  |
1229|     6500     |   7   |  2017  |
1229|     7800     |   5   |  2016  |
1312|    110000    |   8   |  2017  |
1312|    120000    |   5   |  2017  |
1312|     99000    |   5   |  2016  |

我试过这个:

select id, year, month, avg(cost) as Avg Cost
from price_history
group by id, year, month
order by id, year desc, month desc

我如何能够显示这样的最新数据:

 ID |     Cost     | Month |  Year  |
-------------------------------------
1081|     13000    |   5   |  2017  |
1229|     6500     |   7   |  2017  |
1312|    110000    |   8   |  2017  |

2 个答案:

答案 0 :(得分:1)

select id, year, month, cost
  from (
    select id, year, month, cost,
           row_number() over(partition by ID order by year desc, month desc) as RN
      from price_history
 ) X
 where RN=1

答案 1 :(得分:0)

结合使用RIGHT / LEFTMAX和连接功能,可以正确分组日期。

SELECT "ID", AVG("Cost") AS "Avg Cost", RIGHT(MAX("Year"::text || "Month"::text),1) AS "Month", LEFT(MAX("Year"::text || "Month"::text),4) AS "Year"
FROM price_history
GROUP BY "ID"
ORDER BY "ID"

输出

ID   Avg Cost           Month Year
1081 15833.333333333332 5     2017
1229 7150               7     2017
1312 109666.66666666667 8     2017

SQL小提琴:http://sqlfiddle.com/#!15/3ebe7/20/0

ROUND ing:

SELECT "ID", ROUND(AVG("Cost")) AS "Avg Cost", RIGHT(MAX("Year"::text || "Month"::text),1) AS "Month", LEFT(MAX("Year"::text || "Month"::text),4) AS "Year"
FROM price_history
GROUP BY "ID"
ORDER BY "ID"

输出

ID   Avg Cost Month Year
1081 15833    5     2017
1229 7150     7     2017
1312 109667   8     2017

SQL小提琴:http://sqlfiddle.com/#!15/3ebe7/21/0