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

Viewed 553

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  |
2 Answers
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.

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

Or with 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"

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

Related