简体   繁体   中英

How to extract the time from a timestamp without timezone column?

I want to calculate the number of orders per each time interval for each day.

The format of the date is timestamp without timezone. I can't seem to extract only the time. I use this query for each day, but is there a way to have the time intervals for each day in the month in one table?

CASE WHEN date_created_utc >= timestamp '2020-09-01 08:00:00' AND date_created_utc <= timestamp '2020-09-01 11:00:00' THEN 'Q1'    
WHEN date_created_utc >= timestamp '2020-09-01 11:00:01' AND date_created_utc <= timestamp '2020-09-01 14:00:00' THEN 'Q2'    
WHEN date_created_utc >= timestamp '2020-09-01 14:00:01' AND date_created_utc <= timestamp '2020-09-01 16:00:00' THEN 'Q3'    
WHEN date_created_utc >= timestamp '2020-09-01 16:00:01' AND date_created_utc <= timestamp '2020-09-01 20:00:00' THEN 'Q4'    
WHEN date_created_utc >= timestamp '2020-09-01 20:00:01' AND date_created_utc <= timestamp '2020-09-01 23:59:00' THEN 'Q5'    
END AS interval,    
COUNT(id) as cnt    
FROM order_processing    
GROUP BY 1;

The desired output table:

Day Q1  Q2  Q3  Q4  Q5
1   28  57  50  65  27
2   23  50  60  90  66
3   58  60  80  70  67

You just need the hour part to implement the logic: you can use extract() :

select
    date_created_utc::date day,
    count(*) filter(where extract(hour from date_created_utc) between 8 and 10) q1,
    count(*) filter(where extract(hour from date_created_utc) between 11 and 14) q2,
    ...
from order_processing
group by date_created_utc::date

You can convert to a time and then use comparisons. For aggregation:

COUNT(*) FILTER (WHERE date_created_utc::time >= '08:00:00' and date_created_utc::time < '11:00:00') as cnt_1
   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM