代码之家  ›  专栏  ›  技术社区  ›  jackstraw22

在Postgres中将多个值合并到一个单元格中

  •  1
  • jackstraw22  · 技术社区  · 7 年前

    我有一个数据集,可以包含多个具有相同索赔编号和不同名称的行:

       claim_id           name
        112               John Smith
        112               Tom Harris
        113               Randy Dugar
    

        claim_no          name
        112               John Smith, Tom Harris
        113               Randy Dugar
    

       with firstrun as(
       select distinct kia.claim_id as claim_id,  c.first_name ||' '  
       ||c.last_name as name
       from kia
       inner join
       claims c
       on kia.claim_id = c.claim_id
    
    
       )
    
       select distinct claim_id, substring((Select ',' || ' '|| fr.name as   text()]
       from firstrun fr
       for xml path('')), 2, 500)
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Mureinik    7 年前

    这个 string_agg 聚合功能将为您完成所有繁重的工作:

    SELECT   claim_id, STRING_AGG(name, ', ')
    FROM     claims
    GROUP BY claim_id