Tuesday, 15 April 2014

Sql Postgres double group by -



Sql Postgres double group by -

i've got table 3 columns: place_id, date, value. each place each date there value, 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 find each month sum of max value places. in context of info above should looks (don't matter how date must showed - 2 columns year , month or 1 column 'yyyy-mm-01'):

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

as got, have utilize grouping twice - firstly maximum value month , place, secondly summarize maximums got on first step. way allow me best performance?

p.s. if it's matter, i'm using postgresql 9.2

i don't see alternatives using subquery. postgres datetrunc() function can help grouping values base of operations table month, seems want do.

select month, sum(max_value) sum_of_max ( select place_id, datetrunc('month', date) month, max(value) max_value my_table grouping place_id, month ) grouping month

sql group-by postgresql-9.2

No comments:

Post a Comment