Select 一行,每个 id 在 sql odoo 查询中

Select one row, each one id in sql query for odoo

我有一个 table 这样的:

 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  |

结合使用 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 Fiddle: http://sqlfiddle.com/#!15/3ebe7/20/0

ROUNDing:

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 Fiddle: http://sqlfiddle.com/#!15/3ebe7/21/0

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