PostgreSQL 9.1: How to concatenate rows in array without duplicates, JOIN another table

前端 未结 1 2106
梦谈多话
梦谈多话 2020-12-14 07:42

I am using PostgreSQL 9.1 and need help with concatenating multiple rows in one. I need to do that in 2 tables. When I use two times array_agg() functions I get

相关标签:
1条回答
  • 2020-12-14 08:00

    Instead of using window functions and patitioning, use a query-level GROUP BY and aggregate with a DISTINCT clause:

    SELECT         
      rnp.grp_id,
      array_to_string(array_agg(distinct rnp.cabinets),',') AS cabinets,
      array_to_string(array_agg(distinct ips.address),',')  AS addresses
    FROM rnp JOIN ips ON rnp.grp_id=ips.grp_id GROUP BY rnp.grp_id, ips.grp_id;
    

    Result:

     grp_id |        cabinets         | addresses 
    --------+-------------------------+-----------
         11 | cabs1,cabs2,cabs3,cabs4 | CA,NY
         22 | c1,c2                   | DC,LA
    (2 rows)
    

    The key here is that instead of using window functions and patitioning, you use a query-level GROUP BY and aggregate with a DISTINCT clause.

    This'd work with the window function approach too, except that PostgreSQL (9.1 at least) doesn't support DISTINCT in window functions:

    regress=# SELECT DISTINCT
      rnp.grp_id,
      array_to_string(array_agg(distinct rnp.cabinets)OVER (PARTITION BY rnp.grp_id), ',') AS cabinets,                    
      array_to_string(array_agg(distinct ips.address) OVER (PARTITION BY ips.grp_id), ',') AS addresses
    FROM rnp JOIN ips ON rnp.grp_id=ips.grp_id;
    ERROR:  DISTINCT is not implemented for window functions
    LINE 3:   array_to_string(array_agg(distinct rnp.cabinets)OVER (PART...
    
    0 讨论(0)
提交回复
热议问题