Using separate dates and aggregate functions with postgres

I am trying to get a set of averages for each month. I use DATE_TRUNC to convert a date to a month only to a month, but I still can't get a great DATE to work. It seems to completely ignore him.

I only need 6 rows, one for each month in RANGE, but instead I get 1000.

SELECT DISTINCT(date_trunc('month', event_logs.start_at)) AS start_at, 
AVG(event_logs.head_count) as head_count FROM "event_logs" 
WHERE ("event_logs"."state" IN ('completed')) AND ("event_logs"."start_at" 
BETWEEN '2013-05-09 10:12:58.824846' AND '2013-11-09') 
GROUP BY start_at

Also tried to throw away DISTINCT (DATE (date_trunc ()), but it didn’t do anything? Is there anything special with DATES that I don’t see?

+----+---------------------+---------------------------+
| id | head_count          | start_at                  |
+----+---------------------+---------------------------+
|    | 17.0                | 2013-06-01 01:00:00 +0100 |#WHY???!?!?!
|    | 15.0                | 2013-06-01 01:00:00 +0100 |#YOU ARE CLONES!
|    | 40.5                | 2013-06-01 01:00:00 +0100 |#NOT DISTINCT!
|    | 32.5                | 2013-10-01 01:00:00 +0100 |
|    | 69.0                | 2013-08-01 01:00:00 +0100 |
|    | 34.9                | 2013-10-01 01:00:00 +0100 |
|    | 9.0                 | 2013-07-01 01:00:00 +0100 |
+4
source share
1 answer

Try the following:

SELECT
date_trunc('month', event_logs.start_at) AS start_at, 
AVG(event_logs.head_count) as head_count 
FROM "event_logs" 
WHERE ("event_logs"."state" IN ('completed')) 
AND ("event_logs"."start_at" 
BETWEEN '2013-05-09 10:12:58.824846' AND '2013-11-09') 
GROUP BY date_trunc('month', event_logs.start_at)

GROUP BY. /. DISTINCT GROUP BY

+5

All Articles