【问题标题】:How to select values from many rows that has the same id to just one row and separate them with -? [duplicate]如何从具有相同 id 的多行中选择仅一行的值并用 - 分隔它们? [复制]
【发布时间】:2019-12-08 12:55:48
【问题描述】:

我想在一行中显示具有相同 id 的表的值,并用- 分隔它们,或者,

 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

【问题讨论】:

  • 您使用的是 MySQL 还是 Postgres?它们是不同的数据库。
  • 对不起,我用的是postgres
  • 真的还在使用 Postgres 9.1 吗?在这种情况下,您应该立即计划升级到当前(支持的)版本。

标签: sql postgresql postgresql-9.1 string-aggregation


【解决方案1】:

您可以使用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

【讨论】:

  • 编译器说“函数 string_agg() 不存在”
  • @RezaPratama 是的,需要转换为 varchar。
【解决方案2】:

使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多