Sql 查询以检索每小时计数,如果没有,则为零
我正在想方设法,但到目前为止还没有成功 我的数据如下所示。我正在使用postGreSQLSql 查询以检索每小时计数,如果没有,则为零,sql,postgresql,Sql,Postgresql,我正在想方设法,但到目前为止还没有成功 我的数据如下所示。我正在使用postGreSQL order_id | create_date -----+-------------------- 6000 | 2013-05-09 11:53:04 6001 | 2013-05-09 12:58:00 6002 | 2013-05-09 13:01:08 6003 | 2013-05-09 13:01:32 6004 | 2013-05-09
order_id | create_date
-----+--------------------
6000 | 2013-05-09 11:53:04
6001 | 2013-05-09 12:58:00
6002 | 2013-05-09 13:01:08
6003 | 2013-05-09 13:01:32
6004 | 2013-05-09 14:05:06
6005 | 2013-05-09 14:06:25
6006 | 2013-05-09 14:59:58
6007 | 2013-05-09 19:00:07
我需要一个查询,该查询生成所有24小时内每小时的订单数。如果一小时内没有订单,查询输出默认为零。下面应该是输出格式
orders | hour
-----+--------------------
0 | 00:00
0 | 01:00
0 | 02:00
0 | 03:00
0 | 04:00
0 | 05:00
0 | 06:00
0 | 07:00
0 | 08:00
0 | 09:00
0 | 10:00
1 | 11:00
1 | 12:00
2 | 13:00
3 | 14:00
0 | 15:00
0 | 16:00
0 | 17:00
0 | 18:00
1 | 19:00
0 | 20:00
0 | 21:00
0 | 22:00
0 | 23:00
有可能吗?下面是我目前的问题。当然,这并不是以我所希望的方式给出输出
select count(order_id) as orders, date_trunc('hour', create_date) as hr from order_table where date_trunc('day', create_date)='2013-05-09' GROUP BY date_trunc('hour', create_date);
使用数字CTE(Postgresql示例):
使用Nums(NN)作为
(
值(0)
联合所有
选择NN+1
其中NN您需要生成小时数。下面是使用generate_series()
的一种方法:
或者:
select g.dte, count(order_id) as orders
from generate_series('2013-05-09'::timestamp, '2013-05-09 23:00:00'::timestamp, interval '1 hour') g(dte) left join
order_table ot
on g.dte = date_trunc('hour', create_date)
group by g.dte
order by g.dte;
我还能给你一个答案吗?测试,测试,哦,是的。好吧,我认为你的查询中的问题是你的比较是错误的:date\u-trunc('day',create\u-date)='2013-05-09'
应该是:date\u-trunc('day',create\u-date='2013-05-09 00:00'
SELECT COUNT(order_id) as orders,
date_trunc('hour',create_date) as hr
FROM order_table
WHERE date_trunc('day', create_date) = '2013-05-09 00:00:00'
GROUP BY date_trunc('hour',create_date);
但是,这不会返回零计数,但是其他人已经解决了这个问题。您使用的是哪种DBMS?MySQL还是PostgreSQL?另外,您可以发布表模式吗?我使用的是PostgreSQL这可能会有所帮助。@O.Jones这不是MySQL,是PostgreSQL我在问题仍然有MySQL标记的情况下关闭了它。我已经指定它重新打开。其他s也可以这样做。它会给我一个错误,比如“列“nn”不存在。我需要用日期替换nn吗?在第一次查询输出中,小时列的输出格式为“01:00:00”。我们如何将其更改为“01:00”?
select g.dte, count(order_id) as orders
from generate_series('2013-05-09'::timestamp, '2013-05-09 23:00:00'::timestamp, interval '1 hour') g(dte) left join
order_table ot
on g.dte = date_trunc('hour', create_date)
group by g.dte
order by g.dte;
SELECT COUNT(order_id) as orders,
date_trunc('hour',create_date) as hr
FROM order_table
WHERE date_trunc('day', create_date) = '2013-05-09 00:00:00'
GROUP BY date_trunc('hour',create_date);