首页 > 解决方案 > 在 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()',但它只返回苹果和米饭行。

标签: sqlpostgresql

解决方案


我发现这很棘手,因为我不知道如何在 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。


推荐阅读