PostgreSQL unnest、int4range和where子句
我有一个名为PostgreSQL unnest、int4range和where子句,sql,arrays,postgresql,unnest,Sql,Arrays,Postgresql,Unnest,我有一个名为mytable的数据表: ╔════╤══════════════════════════════╤══════════╗ ║ id │ segments │ duration ║ ╠════╪══════════════════════════════╪══════════╣ ║ 1 │ {"[1,4)","[6,13)","[15,19)"} │ 14 ║ ╟────┼─────────────────────────────
mytable
的数据表:
╔════╤══════════════════════════════╤══════════╗
║ id │ segments │ duration ║
╠════╪══════════════════════════════╪══════════╣
║ 1 │ {"[1,4)","[6,13)","[15,19)"} │ 14 ║
╟────┼──────────────────────────────┼──────────╢
║ 2 │ {"[3,16)","[19,22)"} │ 16 ║
╚════╧══════════════════════════════╧══════════╝
段
是以秒为单位的时间间隔数组。duration
是段中时间间隔的总和,单位为秒
例如,对于id
=1,段中的三个间隔分别为3、7和4秒。它们在持续时间内总共14秒
我只想从此表中提取满足这两个条件的行:
- 没有不少于10秒的单个
段
- 持续时间至少为10秒
查询应仅返回id
=1,因为其单个段
都小于10秒,且其持续时间至少为10秒
查询不应返回id
=2,因为其段之一的长度为13秒。其持续时间
至少为10秒,但它不满足有关段的第一个条件
在横向联接中取消数组的测试,并按id
分组计算和。使用布尔聚合bool_和()
select id, segments, sum(elem.upper- elem.lower) as duration
from my_table
cross join unnest(segments) elem
group by id
having bool_and(elem.upper- elem.lower < 10)
and sum(elem.upper- elem.lower) >= 10
选择id、段、和(elem.upper-elem.lower)作为持续时间
从我的桌子上
交叉连接未安装(段)元素
按id分组
具有布尔和(上元素-下元素<10)
和(上元素-下元素)>=10
您可以进行横向连接:
select t.*
from mytable t
inner join lateral (
select bool_and(seg.upper - seg.lower < 10) to_keep
from unnest(t.segments) seg
) x on x.to_keep
where t.duration >+ 10
您存储的是字符串数组还是嵌套的数字数组?我不清楚您对数据的表示。嵌套数字数组。数据类型为int4range。
id | segments | duration
-: | :--------------------------- | -------:
1 | {"[1,4)","[6,13)","[15,19)"} | 14