对列值的更改date_trunc进行不同的搜索

时间:2014-11-17 09:40:31

标签: sql postgresql datetime count

简短而简单,我希望获得一个独特小时列表及其计数代表。

SELECT DISTINCT(date_trunc('hour', occurred)) as time, COUNT(*)
  FROM log
  WHERE occurred BETWEEN '2014-01-01 00:00' AND '2014-01-01 23:59'
GROUP BY occurred;

这不起作用,因为我获得了比24更多的结果 所以我继续尝试:

SELECT DISTINCT(occurred), COUNT(*)
    FROM log
    WHERE occurred BETWEEN .. AND ..
GROUP BY date_trunc('hour', occurred);

这是一种无效的语法,显然我只是在扯动它,因此我需要帮助。 如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您根本不需要DISTINCT

如果您只对发生任何事情的“小时”列表感兴趣(适用于任何时间范围):

SELECT date_trunc('hour', occurred) AS hour, COUNT(*) AS ct
FROM   log
WHERE  occurred >= '2014-01-01 0:0'
AND    occurred <  '2014-01-02 0:0'  -- do not use between for this
GROUP  BY 1
ORDER  BY 1;

BETWEEN包括上限和下限,通常不适用于时间戳范围:

如果一个多小时没有任何反应怎么办?如果您仍然希望结果中的行没有活动几小时(忽略此变体中的日期!):

SELECT hour, COUNT(l.occurred) AS ct
FROM   generate_series (0,23) h(hour)
LEFT   JOIN log l ON occurred >= '2014-01-01 0:0'
                 AND occurred <  '2014-01-02 0:0'  -- do not use between for this
                 AND EXTRACT(hour FROM occurred)::int = h.hour
GROUP  BY hour
ORDER  BY hour;

generate_series()每天提供完整的小时数 LEFT JOIN保留了所有这些内容 仅计算实际日志条目。