【问题标题】:SQL query to get distinct values from grouped records of each columnSQL查询从每列的分组记录中获取不同的值
【发布时间】:2020-05-21 18:38:14
【问题描述】:

假设,我有一张歌单

Table name: Songs
- id
- artist
- composer
- lyricist

我想编写一个 sql 查询,以便我可以从按 id 分组的记录中获取不同的值。 示例:

Id Artist Composer Lyricist
1  a1      c1       l1
1  a2      c1       l1
1  a1      c2       l1
2  a3      c1       l2
2  a4      c1       l3

查询应该返回

Id Artist Composer Lyricist
1  a1, a2  c1, c2   l1
2  a3, a4  c1       l2, l3

如果我可以获得通用 SQL 查询,即不特定于某些数据库功能,那就太好了。请注意,不同表中的列可能会有所不同,所以最好不要在查询中写下每个列名。

如果有人可以提出建议,请。

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 在这里,我正在使用 Postgresql,但想要一个通用的 sql 查询,适用于任何关系数据库。

标签: sql postgresql


【解决方案1】:

Postgres SQL 版本使用string_agg()array_agg()

select id,
       string_agg(distinct artist, ','),
       string_agg(distinct composer, ','),
       string_agg(distinct lyricist, ',')
from t
group by id;

通用 SQL 版本称为listagg()

【讨论】:

  • 是的,我同意。但是,我实际上不想特定于列查询,我在问题中提到过它。我想要的是,如果假设我有更多列的不同表,它应该自动更新,我不应该自己写 listagg 中的每一列。
猜你喜欢
  • 2010-09-21
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多