简体   繁体   中英

Sql Postgres double group by

I've got table with three columns: place_id, date, value. For each place for each date there is value, for example

place_id: 1, date: '2014-01-01', value: 1
place_id: 2, date: '2014-01-01', value: 2
place_id: 1, date: '2014-02-02', value: 3
place_id: 1, date: '2014-02-03', value: 4
place_id: 2, date: '2014-02-15', value: 5

My goal is to find for each month sum of max value for all places. In the context of data above it should looks like (don't matter how date must be showed like - as two columns year and month or one column 'yyyy-MM-01'):

date: '2014-01-01', sum_of_max: 3
date: '2014-02-01', sum_of_max: 9

As I got, I have to use group by twice - firstly to get maximum value for month and place, secondly to summarize maximums I got on first step. But what way let me do it with best performance?

PS If it's matter, I'm using PostgreSql 9.2

I don't see good alternatives to using a subquery. The Postgres datetrunc() function can help with grouping values from your base table by month, as it seems you want to do.

SELECT month, SUM(max_value) AS sum_of_max
FROM (
  SELECT place_id, date_trunc('month', date) AS month, MAX(value) AS max_value
  FROM my_table
  GROUP BY place_id, month
  ) mx
GROUP BY month

One way is a subquery with two group by :

select mm, sum(maxvalue)
from (select place_id, date_trunc('month', date) as mm, max(value) as maxvalue
      from table t
      group by place_id, date_trunc('month', date)
     ) t
group by mm;

Using distinct on in the subquery will probably give better performance:

select mm, sum(maxvalue)
from (select distinct on (place_id, date) place_id, date_trunc('month', date) as mm,
             max(value) as maxvalue
      from table t
      order by place_id, date_trunc('month', date), value desc
     ) t
group by mm;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM