按时分组小时

时间:2011-11-07 21:11:15

标签: postgresql

我需要在一组记录中获取当天最常见的时刻(黎明,早晨,傍晚,夜晚)。我正在尝试使用CASE-WHEN对结果进行分组,但我无法比较日期和整数。我试试这个:

SELECT done_at,
  case done_at
  when date_trunc('hour', done_at) > 0 and date_trunc('hour', done_at) <= 7 then
    'dawn'
  when dayhour > 7 and dayhour <= 12 then
    'morning'
  when dayhour > 12 and dayhour <= 20 then
    'evening'
  when dayhour > 20 and dayhour <= 00 then
    'night'
  end
FROM iterations;

但是我得到了这个错误:

PGError: ERROR:  operator does not exist: timestamp without time zone > integer
LINE 3:       when date_trunc('hour', done_at) > 0 and date_trunc('h...

我也尝试将类型转换为整数,但我明白了:

PGError: ERROR:  cannot cast type timestamp without time zone to integer
LINE 3:       when date_trunc('hour', done_at)::integer > 0 and date...

事实上,done_at确实有一个时区。从Rails控制台:

?> Iteration.first.done_at
=> Fri, 23 Sep 2011 02:00:00 CEST +02:00

现在我很无能为力。

获取当天时刻的任何提示或任何其他方法?

2 个答案:

答案 0 :(得分:2)

查询可能如下所示:

SELECT CASE 
        WHEN h > 0  AND h <= 7  THEN 'dawn'
        WHEN h > 7  AND h <= 12 THEN 'morning'
        WHEN h > 12 AND h <= 20 THEN 'evening'
        WHEN h > 20             THEN 'night'
       END AS moment
       ,count(*) AS cnt
FROM  (
    SELECT extract(hour from done_at) AS h
    FROM   iterations
    ) x
GROUP  BY 1
ORDER  BY count(*) DESC
LIMIT  1;

主要方面:

  • @lanzz关于extract()
  • 是对的
  • 使用子查询计算一天中的小时数,以大大简化代码。
  • GROUP BY, count, ORDER BYLIMIT可以在一个查询级别发生。
  • 结果是当天最常见的时刻

答案 1 :(得分:1)

您希望extract(hour from done_at)代替date_trunc('hour', done_at)