【问题标题】:Is there a way to count combination of columns in PostgreSQL?有没有办法计算 PostgreSQL 中的列组合?
【发布时间】:2021-12-15 21:10:34
【问题描述】:

我有一个名为 MEMBER 的 Postgres 表,其中包含 3 列,如下所示:

id_musician id_band instrument
1 1 Guitar
1 1 Vocals
2 3 Vocals
2 4 Vocals
2 4 Guitar
3 1 Guitar

我需要计算每个成员是/曾经是多少个乐队的成员。有没有办法计算这个?

我尝试了下一个代码:

SELECT DISTINCT e.id_musician,count(id_band)
FROM MEMBER e
GROUP BY e.id_musician, e.instrument
ORDER BY e.id_musician;

但它给了我这个结果:

id_musician count
1 1
2 1
2 2
3 1

例如,我想知道每个成员有多少个乐队

id_musician count
1 1
2 2
3 1

但音乐家 2 上没有双排

有什么建议吗?

【问题讨论】:

    标签: sql postgresql group-by count subquery


    【解决方案1】:

    你可以使用count(distinct id_band):

    select id_musician, count(distinct id_band) from members group by id_musician;
    

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2022-01-14
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多