gpt4 book ai didi

sql - Oracle查询时间范围

转载 作者:行者123 更新时间:2023-12-02 00:05:22 24 4
gpt4 key购买 nike

下面是我自己的练习:

我创建了一个包含一些值的表,如:

CREATE TABLE my_test AS
SELECT ROWNUM ID, TRUNC(SYSDATE)+(LEVEL*5/24/60/60)date_time , 111 person_id
FROM dual CONNECT BY LEVEL <= (24*60*60)/5
ORDER BY 1;

现在,我更新了表格,person_id = 222对于 date_time5:30 am 之间和 6:30 am

UPDATE my_test
SET person_id = 222
WHERE date_time >= trunc(SYSDATE)+ 5/24 + 30/24/60
AND DATE_TIME <= trunc(sysdate)+ 6/24 + 30/24/60;

我需要统计每个小时的人数,所以我写了这样的代码:

SELECT time_range,count(distinct person_id) PERSON_COUNT
FROM (
select person_id , date_time,
case TO_CHAR(date_time,'hh24') when '00' then '12 AM - 01 AM'
when '01' then '01 AM - 02 AM'
when '02' then '02 AM - 03 AM'
when '03' then '03 AM - 04 AM'
when '04' then '04 AM - 05 AM'
when '05' then '05 AM - 06 AM'
when '06' then '06 AM - 07 AM'
when '07' then '07 AM - 08 AM'
when '08' then '08 AM - 09 AM'
when '09' then '09 AM - 10 AM'
when '10' then '10 AM - 11 AM'
when '11' then '11 AM - 12 PM'
when '12' then '12 PM - 01 PM'
when '13' then '01 PM - 02 PM'
when '14' then '02 PM - 03 PM'
when '15' then '03 PM - 04 PM'
when '16' then '04 PM - 05 PM'
when '17' then '05 PM - 06 PM'
when '18' then '06 PM - 07 PM'
when '19' then '07 PM - 08 PM'
when '20' then '08 PM - 09 PM'
when '21' then '09 PM - 10 PM'
when '22' then '10 PM - 11 PM'
WHEN '23' THEN '11 PM - 12 AM' end time_range
FROM my_test
WHERE date_time >= trunc(SYSDATE)
AND date_time < trunc(SYSDATE)+1
ORDER BY date_time)
GROUP BY time_range;

它在没有预期顺序的情况下工作正常。 (time_range 的顺序没有给出预期的结果,因为它是外部查询中的字符串)。

我需要按 time_range 进行排序,感谢任何简单易用的上述代码。提前致谢。

最佳答案

ORDER BY 子句在单个查询中始终是最后解释的,但是这里它在子查询中,因此主查询 GROUP BY 将“覆盖”您的 ORDER BY

你可以这样写:

SELECT time_range, COUNT(DISTINCT person_id) PERSON_COUNT
FROM (SELECT person_id,
date_time,
CASE TO_CHAR(date_time, 'hh24')
WHEN '00' THEN
'12 AM - 01 AM'
/*[snip]*/
WHEN '23' THEN
'11 PM - 12 AM'
END time_range
FROM my_test
WHERE date_time >= trunc(SYSDATE)
AND date_time < trunc(SYSDATE) + 1)
GROUP BY time_range, TO_CHAR(date_time, 'hh24')
ORDER BY TO_CHAR(date_time, 'hh24');

此外,我不喜欢您的 time_range 表达式。您可以简单地将其重写为:

to_char(date_time, 'HH PM - ') || to_char(date_time + 1/24, 'HH PM') time_range

编辑:显然你需要完整的查询:

SELECT time_range, COUNT(DISTINCT person_id) PERSON_COUNT
FROM (SELECT person_id,
date_time,
to_char(date_time, 'HH PM - ')
|| to_char(date_time + 1/24, 'HH PM') time_range
FROM my_test
WHERE date_time >= trunc(SYSDATE)
AND date_time < trunc(SYSDATE) + 1)
GROUP BY time_range, TO_CHAR(date_time, 'hh24')
ORDER BY TO_CHAR(date_time, 'hh24');

关于sql - Oracle查询时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18739543/

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