2013-11-09 58 views
4

我試圖得到一組平均每個月。我正在使用DATE_TRUNC將日期時間轉換爲月份年,但我仍然無法獲得明確的日期。似乎完全忽略它。使用不同的日期和聚合函數與postgres

我只想要6行,每個月在RANGE中有一個,但是我得到了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 

也試過在DISTINCT投擲(DATE(date_trunc()),但沒有做任何事情是不是有什麼特殊的日期,我沒有看到

+----+---------------------+---------------------------+ 
| 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 | 
+0

您的'GROUP BY start_at'組按原始時間戳記,而不是按日期彙總的時間戳記 – wildplasser

回答

5

試試這個:

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語句。你需要GROUP BY個月,而不是日期/時間值。而你並不需要使用DISTINCT與GROUP BY