This question already has answers here:
Postgresql GROUP_CONCAT equivalent?
(6个答案)
How to concatenate strings of a string field in a PostgreSQL 'group by' query?
(14个答案)
4个月前关闭。
我想在一行中显示具有相同i d的表的值,并用-分隔它们,或者,
 row id | base_id | auth_id
--------+---------+---------
      4 |       1 |       1
      5 |       1 |       3
      6 |       2 |       2
      7 |       2 |       6
      8 |       2 |       5

我期待的结果
 row id | base_id | auth_id
--------+---------+---------
      1 |       1 | 1-3
      2 |       2 | 2-6-5

最佳答案

您可以使用string_agg()连接和row_number()窗口分析函数:

select row_number() over (order by base_id) as row_id,
       base_id, string_agg(auth_id::varchar,'-' order by auth_id) as auth_id
  from tab
 group by base_id;

Demo

10-01 23:27