我正试图获得每月的一组平均值。我正在使用DATE_TRUNC将日期时间转换为月份,但我仍然无法使用不同的DATE。似乎完全忽略它。
我只需要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())但是没有做任何事情吗?DATES有什么特别的东西我没有看到吗?
+----+---------------------+---------------------------+
| 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 :(得分: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一起使用