我想实现以下目标:
从时间戳我想指出时间部分落在哪个时间间隔之下。 08:00:00 - 12:59:59,13:00:00-17:59:59,18:00~22:59:59等整个想法都缠绕着我想确定什么时间在一天,一个网站主要访问。我使用cast(timestamp as time)
它不起作用,我做了select '2018-05-25 12:00:00'::time
它确实提取了时间,但只有当它在文本中输入而不是列名时,我希望使用'假设这段代码正在工作':
select timestamp::time between '08:00:00'::time and '12:59:59'
我最初的解决方案是,我的经理说这是错误的。
sum(case when cast(substring(split_part(event_date, ' ', 2),1,2) as int) in (23,00,01,02,03,04) then 1 else 0 end) as time_23_04,
sum(case when cast(substring(split_part(event_date, ' ', 2),1,2) as int) between 5 and 7 then 1 else 0 end) as time_05_07,
sum(case when cast(substring(split_part(event_date, ' ', 2),1,2) as int) between 8 and 12 then 1 else 0 end) as time_08_12,
sum(case when cast(substring(split_part(event_date, ' ', 2),1,2) as int) between 13 and 17 then 1 else 0 end) as time_13_17,
sum(case when cast(substring(split_part(event_date, ' ', 2),1,2) as int) between 18 and 22 then 1 else 0 end) as time_18_22
答案 0 :(得分:1)
你可以extract dateparts using EXTRACT():
SELECT
SUM(CASE WHEN MOD(EXTRACT(HOUR FROM event_date), 23) BETWEEN 0 AND 4 THEN 1 END) AS time_23_04,
SUM(CASE WHEN EXTRACT(HOUR FROM event_date) BETWEEN 5 AND 7 THEN 1 END) AS time_05_07,
SUM(CASE WHEN EXTRACT(HOUR FROM event_date) BETWEEN 8 AND 12 THEN 1 END) AS time_08_12,
SUM(CASE WHEN EXTRACT(HOUR FROM event_date) BETWEEN 13 AND 17 THEN 1 END) AS time_13_17,
SUM(CASE WHEN EXTRACT(HOUR FROM event_date) BETWEEN 18 AND 22 THEN 1 END) AS time_18_22
FROM table
第一行是我的一点乐趣。它与您的IN语句相同。
此外,如果CASE
语句找不到匹配项,则返回NULL
,SUM
会忽略该语句。