我在 POSTGRE 中有一個名為 MEMBER 的表,其中包含 3 列,如下所示:
| id_musician | id_band | 儀器 |
|---|---|---|
| 1 | 1 | 吉他 |
| 1 | 1 | 人聲 |
| 2 | 3 | 人聲 |
| 2 | 4 | 人聲 |
| 2 | 4 | 吉他 |
| 3 | 1 | 吉他 |
我需要計算每個成員是/曾經是多少個樂隊的成員。有沒有辦法計算這個?
我嘗試了下一個代碼:
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 | 數數 |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
例如,我想獲得每個成員有多少個樂隊
| id_musician | 數數 |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
但沒有音樂家 2 的雙排
有什么建議?
uj5u.com熱心網友回復:
您可以使用count(distinct id_band):
select id_musician, count(distinct id_band) from members group by id_musician;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343249.html
標籤:sql PostgreSQL 通过...分组 数数 子查询
