Postgres每小时最小/最大

时间:2016-10-21 07:07:52

标签: postgresql timestamp

嗨我有一个表名称令牌,它会生成像这样生成的令牌数据

\Symfony\Component\Translation\MessageCatalogue

和像这样的表token_queue具有一对一的关系

id     | generated_time          | token_name
461087 | 2016-10-21 09:02:53.951 |  G1  
461088 | 2016-10-21 09:31:13.469 |  C1
461089 | 2016-10-21 09:31:15.711 |  C2  
461090 | 2016-10-21 10:37:17.73  |  C3
461091 | 2016-10-21 10:02:53.951 |  G2  
461092 | 2016-10-21 10:15:13.469 |  C4
461093 | 2016-10-21 11:22:15.611 |  C5  
461094 | 2016-10-21 11:31:14.743 |  C6

现在我想从令牌表中显示每小时-24小时(current_date)的最小值/最大值,并从token_queue计算最小值/最大值,即

serving_end_time | serving_start_time | token_id 2016-10-21 09:04:45.681 | 2016-10-21 09:03:49.05 | 461087 2016-10-21 09:33:49.035 | 2016-10-21 09:32:07.996 | 461088 2016-10-21 09:34:42.431 | 2016-10-21 09:32:27.134 | 461089 2016-10-21 10:39:57.775 | 2016-10-21 10:38:37.428 | 461090 2016-10-21 10:04:49.715 | 2016-10-21 10:03:09.972 | 461091 2016-10-21 10:17:28.268 | 2016-10-21 10:16:06.946 | 461092 2016-10-21 11:23:36.036 | 2016-10-21 11:22:30.233 | 461093 2016-10-21 11:32:32.876 | 2016-10-21 11:31:27.044 | 461094
MIN(token_queue.serving_end_time - token_queue.serving_start_time)

这是2016-10-21日期的示例输出

MAX(token_queue.serving_end_time - token_queue.serving_start_time)

感谢您的任何帮助/建议。

1 个答案:

答案 0 :(得分:0)

SELECT date_trunc('hour', t.generated_time) AS hour,
       min(tq.serving_end_time - tq.serving_start_time) AS min,
       max(tq.serving_end_time - tq.serving_start_time) AS max
FROM token t
     JOIN token_queue tq
        ON t.id = tq.token_id
GROUP BY 1
ORDER BY 1;