如何将具有相同 id 的许多行中的值 select 只保留一行并用 - 分隔它们?

How to select values from many rows that has the same id to just one row and separate them with -?

我想在一行中显示具有相同 ID 的 table 的值,并用 -

分隔它们
 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 试试这个选项:

select
    row_number() over (order by base_id) row_id,
    base_id,
    string_agg(auth_id, '-' order by auth_id)
from your_table
group by
    base_id
order by
    base_id;

您可以使用 string_agg() 串联和 row_number() window 解析函数:

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