sql - Postgresql 从日期数组之间的日期范围中选择
问题描述
如果此查询返回请求范围内存在的日期。
select created_at from user where created_at between '2015-01-06 00:00:00.000000' and '2015-03-06 00:00:00.000000'
有没有办法获得这样的结果,但日期数组中包含多个日期。
只是我想说的一个例子。我有这个日期数组,总是会有第一个和最后一个日期。
Array['2015-01-06 00:00:00.000000','2015-02-10 15:17:18.895000' <- First range
'2017-10-05 14:41:04.191000','2017-10-11 14:49:36.454000' <- Second range
那么有没有办法放置一个像这样的脚本?
select created_at from win_users
where (created_at between [First Date] and [Second Date])
or (created_at between [Third Date] and [Fourth Date])
但不使用循环连接 where 语句?
解决方案
在这种情况下,一系列日期非常不舒服。使用数组 ofdaterange
和包含操作符<@
,例如:
with my_table(id, created_at) as (
values
(1, '2015-01-10'::timestamp),
(2, '2016-05-10'),
(3, '2017-10-10')
)
select *
from my_table
where created_at::date <@ any(array[
daterange('2015-01-06','2015-02-10'),
daterange('2017-10-05','2017-10-11')])
id | created_at
----+---------------------
1 | 2015-01-10 00:00:00
3 | 2017-10-10 00:00:00
(2 rows)
如果您绝对想使用日期数组(老实说我不这么认为),请使用此函数将其转换为 daterange 数组:
create or replace function date_pairs_to_ranges(date[])
returns daterange[] language sql as $$
select array_agg(daterange(d1, d2))
from unnest($1) with ordinality as u1(d1, o1)
join unnest($1) with ordinality as u2(d2, o2)
on o1/ 2* 2 < o1 and o2 = o1+ 1
$$;
with my_table(id, created_at) as (
values
(1, '2015-01-10'::timestamp),
(2, '2016-05-10'),
(3, '2017-10-10')
)
select *
from my_table
where created_at::date <@ any(
date_pairs_to_ranges(array[
'2015-01-06','2015-02-10',
'2017-10-05','2017-10-11']::date[]))
推荐阅读
- java - 我想在netbeans中将像“S1001”这样的字符串ID增加到“S1002”
- javascript - 类型 '(d: { value: number }) => number' 不可分配给类型 'number'
- php - 如何使用 Laravel Passport 令牌系统
- c - 用C中范围内的随机数填充数组
- python - ValueError:字段“id”需要一个数字,但得到“超级”。[2020 年 4 月 4 日 18:15:11]“GET /super_user HTTP/1.1”500 132224
- javascript - 如何在生产版本中排除/禁用 React 开发人员工具?
- curl - 使用带有数据的 Runtime.getRuntime.exec 错误在 kotlin 中的 CURL POST 请求
- java - 为什么我在 Google 代码堵塞中遇到运行时错误?
- keras - Streamlit 缓存 Keras 训练模型
- python - 根据使用生物识别设备生成的 CSV 文件计算出勤率