我需要创建一个度量标准,以显示一周中特定日期每小时每小时创建的订单数量。但是,DB中的任何记录都有一段时间。但是我这次仍然需要证明。
select count(id),
date_trunc('hour', created_at at time zone 'US/Pacific')::time as "time"
from "order"
where to_char(created_at, 'day') like '%wed%'
group by date_trunc('hour', created_at at time zone 'US/Pacific')::time
结果,我有这样的东西
计数,时间
| 6 | 00:00:00 |
+-+ ------------ +
| 3 | 01:00:00 |
+-+ ------------ +
| 4 | 03:00:00 |
+-+ ------------ +
| 5 | 05:00:00 |
+-+ ------------ +
但是需要这个
计数,时间
| 6 | 00:00:00 |
+-+ ------------ +
| 3 | 01:00:00 |
+-+ ------------ +
| 0 | 02:00:00 |
+-+ ------------ +
| 4 | 03:00:00 |
+-+ ------------ +
| 0 | 04:00:00 |
+-+ ------------ +
| 5 | 05:00:00 |
+-+ ------------ +
答案 0 :(得分:1)
一种选择是使用包含所有可能时间的日历表,然后加入该日历表:
WITH times AS (
SELECT '00:00:00'::time AS timeval UNION ALL
SELECT '01:00:00'::time UNION ALL
SELECT '02:00:00'::time UNION ALL
...
SELECT '23:00:00'::time
)
SELECT
COUNT(*) AS count,
t.timeval
FROM times t
LEFT JOIN "order" o
ON t.timeval = date_trunc('hour', o.created_at at time zone 'US/Pacific')::time AND
to_char(o.created_at, 'day') LIKE '%wed%'
GROUP BY
t.timeval;
如果您不想报告整整24小时,则只需修改times
CTE以仅包括您想要的小时数即可。
答案 1 :(得分:0)
为什么不这样:
select count(id),
date_trunc('hour', created_at at time zone 'US/Pacific')::time as "time"
from "order"
where to_char(created_at, 'day') like '%wed%' and count(id)=0 or count(id)!=0
group by date_trunc('hour', created_at at time zone 'US/Pacific')::time