将不同行中的一系列值合并为一个

时间:2014-03-05 18:18:30

标签: sql postgresql aggregate-functions

我需要做一个ETL工作,我有一个看起来像这样的表

user_name | role
----------+------
User A    | Admin
User A    | System
User B    | Editor
User B    | Power User
User B    | System

我想将其转换为

user_name | role
----------+------
User A    | Admin, System
User B    | Editor, Power User, System

我考虑过创建临时表并使用row_number() over (partition by user_name),但它开始变得混乱。是否有更好的方法来获得该输出?

2 个答案:

答案 0 :(得分:1)

使用聚合函数string_agg()

SELECT user_name, string_agg("role", ', ') AS roles
FROM   tbl
GROUP  BY 1
ORDER  BY 1;

如果您希望按字母顺序排列列表:

string_agg("role", ', ' ORDER BY "role")

答案 1 :(得分:0)

SELECT user_name, 
 array_to_string(array(
        select role
        from my_table
        where user_name =m.user_name
        order by user_name
        ), ', '
    ) combined_rows
from my_table m

group by 1

链接到SQL Fiddle