有没有办法计算 PostgreSQL 中列的组合?
Is there a way to count combination of columns in PostgreSQL?
我有一个名为 MEMBER 的 Postgres table,它有 3 列,如下所示:
id_musician
id_band
instrument
1
1
Guitar
1
1
Vocals
2
3
Vocals
2
4
Vocals
2
4
Guitar
3
1
Guitar
我需要计算每个 is/was 成员所属的乐队数量。有没有办法算这个?
我尝试了下一个代码:
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 的双排
有什么建议吗?
您可以使用 count(distinct id_band)
:
select id_musician, count(distinct id_band) from members group by id_musician;
我有一个名为 MEMBER 的 Postgres table,它有 3 列,如下所示:
id_musician | id_band | instrument |
---|---|---|
1 | 1 | Guitar |
1 | 1 | Vocals |
2 | 3 | Vocals |
2 | 4 | Vocals |
2 | 4 | Guitar |
3 | 1 | Guitar |
我需要计算每个 is/was 成员所属的乐队数量。有没有办法算这个?
我尝试了下一个代码:
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 的双排
有什么建议吗?
您可以使用 count(distinct id_band)
:
select id_musician, count(distinct id_band) from members group by id_musician;