gpt4 book ai didi

sql - 计算oracle中两个日期之间每小时的记录数

转载 作者:行者123 更新时间:2023-12-03 13:43:00 26 4
gpt4 key购买 nike

我需要一个在 oracle 中执行此序列的 SINGLE 查询。

select count(*) from table1
where request_time < timestamp'2012-05-19 12:00:00' and (end_time > timestamp'2012-05-19 12:00:00' or end_time=null);

select count(*) from table1
where request_time < timestamp'2012-05-19 13:00:00' and (end_time > timestamp'2012-05-19 13:00:00' or end_time=null);

select count(*) from table1
where request_time < timestamp'2012-05-19 14:00:00' and (end_time > timestamp'2012-05-19 14:00:00' or end_time=null);

select count(*) table1
where request_time < timestamp'2012-05-19 15:00:00' and (end_time > timestamp'2012-05-19 15:00:00' or end_time=null);

select count(*) from table1
where request_time < timestamp'2012-05-19 16:00:00' and (end_time > timestamp'2012-05-19 16:00:00' or end_time=null);

如您所见,小时正在一点一点地增加。
这是输出
COUNT(*)               
1085
COUNT(*)               
1233
COUNT(*)               
1407
COUNT(*)               
1322
COUNT(*)               
1237

我写了一个查询,但它没有给我正确的答案!
select col1, count(*) from
(select TO_CHAR(request_time, 'YYYY-MM-DD HH24') as col1 from table1
where request_time <= timestamp'2012-05-19 12:00:00' and (end_time >= timestamp'2012-05-19 12:00:00' or end_time=null))
group by col1 order by col1;

这个查询给了我一个结果集,它的 count(*) 的总和等于上面写的第一个查询!
结果如下:
COL1          COUNT(*)               
------------- ----------------------
2012-05-19 07 22
2012-05-19 08 141
2012-05-19 09 322
2012-05-19 10 318
2012-05-19 11 282

最佳答案

注意trunc的用法带有日期值的表达式。您可以省略 alter session如果您没有在 sql*plus 中运行查询。

SQL> alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';

Session altered.

SQL> SELECT
trunc(created,'HH'),
count(*)
FROM
test_table
WHERE
created > trunc(SYSDATE -2)
group by trunc(created,'HH');


TRUNC(CREATED,'HH') COUNT(*)
------------------- ----------
2012-05-21 09:00:00 748
2012-05-21 16:00:00 24
2012-05-21 17:00:00 12
2012-05-21 22:00:00 737
2012-05-21 23:00:00 182
2012-05-22 20:00:00 16
2012-05-22 21:00:00 293
2012-05-22 22:00:00 610

8 ROWS selected.

关于sql - 计算oracle中两个日期之间每小时的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10714680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com