sql - 在 postgreSQL 识别数组中的序列后返回一个值
问题描述
我需要在数组 B 中找到相应位置,该位置在 postgreSQL 中查询的数组 A 中开始一个序列。
我的数据集看起来像
name A B
apple | {0,0,1} | {x y z}
bean | {0,0,0} | {i h j}
rice | {0,1,0} | {o l ç}
并且序列是0,1
所以我需要那个查询返回
Apple | y
bean |
rice | o
我能怎么做?
我尝试使用'any()',但它只返回苹果和米饭行。
解决方案
我发现这很棘手,因为我不知道如何在 Postgres 中搜索另一个数组并返回索引。所以,这需要一些取消嵌套。
尝试这个:
with t as (
select v.*
from (values ('apple', array[0,0,1], array['x', 'y', 'z']),
('bean', array[0,0,0], array['i', 'h', 'j']),
('rice', array[0,1,0] , array['o', 'l', 'ç'])
) v(name, a, b)),
comparison as (
select v.*
from (values (array[0,1])) v(comp)
)
select name,
min(case when v_array = comp then e end)
from (select v.*, x.*,
(array_agg(d) over (partition by v.name order by x.rn rows between current row and unbounded following))[1:array_length(c.comp, 1)] as v_array,
c.comp
from (values ('apple', array[0,0,1], array['x', 'y', 'z']),
('bean', array[0,0,0], array['i', 'h', 'j']),
('rice', array[0,1,0] , array['o', 'l', 'ç'])
) v(name, a, b) cross join
unnest(a, b) with ordinality x(d, e, rn) cross join
comparison c
) vx
group by name;
这是一个 db<>fiddle。
推荐阅读
- android - 导致崩溃的奇怪启动行为
- regex - 如何(SUM(IF(REGEXMATCH(具有多个条件/条件的IMPORTRANGE?
- html - CSS 文件名有效,但文件路径无效
- php - 无法使用 cURL 删除 SFTP 文件
- php - Laravel 6 验证:规则数量有限制?
- octave - tricontour 与 matlab 版本或 octave clabel 不兼容
- linux - nohup 和 bg 有什么区别?
- python - `functools.update_wrapper` 和 `functools.wraps` 复制的属性超出预期
- javascript - 无法使用 Webpacker 在 Ruby on Rails 6 中调用 Bootstrap4 $('.carousel').carousel
- office-js - 使用 Office.js 自定义 Office Word 上下文的样式