4

我试图获得每个月的一组平均值。我正在使用 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 |
4

1 回答 1

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 语句中。您需要按月分组,而不是日期/时间值。而且您不需要将 DISTINCT 与 GROUP BY 一起使用

于 2013-11-09T12:44:50.160 回答