我有一个包含一系列事件和时间的数据库。
我想知道如何在以下位置编写查询:
cast(date_parse(date_time, ‘%y-%m-%d %h:%i:%s))
在某些日期之间(例如 1/1/22 - 1/1/23)并且时间在(例如早上 6 点 - 下午 3 点)之间
不确定如何合并日期之间以及一天中的特定时间
可以用半开区间过滤日期部分,然后用
extract
查看小时部分:
select *
from mytable
where date_time >= date '2022-01-01'
and date_time < date '2023-01-01'
and extract(hour from date_time) between 6 and 14
此过滤器适用于整个 2022 年,每天早上 6 点(含)到下午 3 点(不含)之间。
WITH
子句)这样你就不需要重复date_parse
:
-- sample data
with dataset (_userid, date_time) as (
values
(329, '22-05-01 05:56:03'),
(329, '22-05-01 12:56:22'),
(329, '22-05-01 12:58:30'),
(329, '22-05-01 15:59:22'),
(329, '22-05-01 15:00:05')
)
-- query
select cast(date_time as date) day,
_userid,
count(*)
from (select _userid,
date_parse(date_time, '%y-%m-%d %H:%i:%s') as date_time -- possibly you will need to "play" with the format
from dataset)
where date_time >= date '2022-01-01'
and date_time < date '2023-01-01'
and extract(hour from date_time) between 6 and 14
group by 1, 2;
输出:
天 | _userid | _col2 |
---|---|---|
2022-05-01 | 329 | 2 |