从2个逗号分隔的字符串中获取公共值的数量

时间:2018-07-13 13:36:07

标签: sql postgresql

我在Postgres的列中有一个表,其中包含逗号分隔的值。

0

现在我想要一个查询,我可以给出一个逗号分隔的字符串,它会告诉我输入字符串和该行中存在的字符串之间的匹配数。

例如,对于输入值ID PRODS -------------------------------------- 1 ,142,10,75, 2 ,142,87,63, 3 ,75,73,2,58, 4 ,142,2, ,我希望输出类似

',142,87,'

4 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT
    *,
    ARRAY(
        SELECT 
            * 
        FROM 
            unnest(string_to_array(trim(both ',' from prods), ',')) 
        WHERE 
            unnest = ANY(string_to_array(',142,87,', ','))
    )
FROM
    prods_table;

输出为:

1   ,142,10,75,     {142}
2   ,142,87,63,     {142,87}
3   ,75,73,2,58,    {}
4   ,142,2,         {142}

cardinality(anyarray)函数添加到最后一列,以获取一些匹配项。

并考虑更改您的数据库设计。

答案 1 :(得分:0)

如果您安装了intarray扩展,这将变得非常容易:

select id, prods, cardinality(string_to_array(trim(prods, ','), ',')::int[] & array[142,87])
from bad_design;

否则,它会更加复杂:

select bd.id, bd.prods, m.matches
from bad_design bd
  join lateral (
    select bd.id, count(v.p) as matches
    from unnest(string_to_array(trim(bd.prods, ','), ',')) as l(p)
      left join ( 
         values ('142'),('87')  --<< these are your input values
      ) v(p) on l.p = v.p
    group by bd.id
  ) m on m.id = bd.id
order by bd.id;

在线示例:http://rextester.com/ZIYS97736

但是您应该真的修正您的数据模型。

答案 2 :(得分:0)

选中此项。

    select T.*,
    COALESCE(No_of_Match,'0')  
    from TT T Left join
    (
        select ID,count(ID) No_of_Match 
        from (
                select ID,unnest(string_to_array(trim(t.prods, ','), ',')) A
                from TT t)a 
        Where A in ('142','87')
        group by ID
    )B
    On T.Id=b.id

Demo Here

  

OutPut

enter image description here

答案 3 :(得分:0)

with data as
( 
select *, 
unnest(string_to_array(trim(both ',' from prods), ',') ) as v
from myTable
),
counts as 
(
select id, count(t) as c from data 
left join 
( select unnest(string_to_array(',142,87,', ',') ) as t) tmp on tmp.t = data.v 
group by id
order by id
)
select t1.id, t1.prods, t2.c as "No. of Match"
from myTable t1
inner join counts t2 on t1.id = t2.id;