select trunc(a.submitted_date,'HH') thehour
, count(1) count_in_hour
from your_order a
LEFT JOIN my_order b ON a.order_id = b.order_id
where a.state!='INCOMPLETE'
and b.substatus != 'DUMMY_IGNORE_INVENTORY'
and a.submitted_date>=trunc(to_date('20/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss'))
and a.submitted_date<=trunc(to_date('21/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss'))
group by trunc(a.submitted_date,'HH')
order by thehour asc;
我需要获取日期之间的订单计数,这会返回我
21-JAN-18 00:00:00 | 3
21-JAN-18 01:00:00 | 4
21-JAN-18 02:00:00 | 5
21-JAN-18 03:00:00 | 6
21-JAN-18 04:00:00 | 7
21-JAN-18 08:00:00 | 7
21-JAN-18 09:00:00 | 4
21-JAN-18 10:00:00 | 9
我没有得到5,6和7个小时的结果,因为这段时间之间没有下订单,但是即使此时未下订单,我也需要查询以将计数返回为0。
就像我需要24行一样,因为日期之间有24小时
答案 0 :(得分:1)
我的方法:
进行基本查询,并期望它将以以下格式提供结果
小时计数_小时_
“ 21-JAN-18 00:00:00” 3
“ 21-JAN-18 01:00:00” 4
我正在编写一个子查询,该查询将在同一日期生成24小时,并对以上结果进行正确的联接。因此,即使您查询的整个24小时都没有获取数据,您也会从此子查询中获得一个条目。
子查询:
尝试以下查询。
select
to_char(to_date('21-JAN-18 00:00:00', 'dd/mm/yyyy HH24:MI:SS') + (level-1)/24, 'DD-MON-YY HH24:MI:SS') as col1
from dual
connect by level <=24;
所有查询:
select
t2.col1,
decode(t1.count_in_hour,null,0,t1.count_in_hour) as count_in_hour
from
(
SELECT
trunc(
a.submitted_date,
'HH'
) thehour,
COUNT(1) count_in_hour
FROM
your_order a
LEFT JOIN my_order b ON a.order_id = b.order_id
WHERE
a.state != 'INCOMPLETE'
AND
b.substatus != 'DUMMY_IGNORE_INVENTORY'
AND
a.submitted_date >= trunc(TO_DATE('20/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss') )
AND
a.submitted_date <= trunc(TO_DATE('21/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss') )
GROUP BY
trunc(
a.submitted_date,
'HH'
)) t1 right join
(select
to_char(to_date('21-JAN-18 00:00:00', 'dd/mm/yyyy HH24:MI:SS') + (level-1)/24, 'DD-MON-YY HH24:MI:SS') as col1
from dual
connect by level <=24
) t2 on t1.thehour = to_date(t2.col1,'DD-MON-YY HH24:MI:SS') order by t2.col1;
答案 1 :(得分:0)
您需要有一个单独的小时表,该小时表可容纳24小时,并且需要与该表联接才能看到计数为0的小时。
CREATE TABLE OrderHours
(
OrderHour CHAR(2)
)
INSERT INTO OrderHours values('00'),('01')..,('24');
select h.OrderHour, count(*)
count_in_hour from OrderHour as h LEFT JOIN your_order a on h.OrderHour = trunc(a.submitted_date,'HH') LEFT JOIN my_order b ON a.order_id = b.order_id where a.order_id = b.order_id
and a.state!='INCOMPLETE' and b.substatus != 'DUMMY_IGNORE_INVENTORY'
and a.submitted_date>=trunc(to_date('20/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss'))
and a.submitted_date<=trunc(to_date('21/01/2018 00:00:00','dd/mm/yyyy hh24:mi:ss')) group by h.OrderHour order by thehour asc;