[英]Select one row, each one id in sql query for odoo
I have a table like this:我有一张这样的表:
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 |
I've tried this:我试过这个:
select id, year, month, avg(cost) as Avg Cost
from price_history
group by id, year, month
order by id, year desc, month desc
How I can show the latest data like this:我如何显示这样的最新数据:
ID | Cost | Month | Year |
-------------------------------------
1081| 13000 | 5 | 2017 |
1229| 6500 | 7 | 2017 |
1312| 110000 | 8 | 2017 |
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
Use a combination of the RIGHT
/ LEFT
, MAX
and concatenation functions to get your dates correctly grouped.使用RIGHT
/ LEFT
、 MAX
和串联函数的组合来正确分组您的日期。
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"
Output输出
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 SQL 小提琴: http ://sqlfiddle.com/#!15/3ebe7/20/0
Or with ROUND
ing:或使用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"
Output输出
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 SQL小提琴: http ://sqlfiddle.com/#!15/3ebe7/21/0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.