以下是我自己的练习:
我创建了一个包含一些值的表,如:
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;
现在,我更新了 table ,person_id = 222
for date_time
between 5:30 am
and6: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 订购,以上任何简单易行的代码都值得赞赏。提前致谢。