MYSQL Select 多个不同值的总和

MYSQL Select the Sum of Multiple Distinct Values

我的 table 看起来像这样:

| id | Vendor | Issue     |
|----|--------|-----------|
| 1  | Acme   | Defective |
| 2  | Best   | Returned  |
| 3  | Ace    | Other     |
| 4  | Best   | Returned  |
| 5  | Acme   | Other     |
| 6  | Ace    | Other     |
| 7  | Best   | Defective |

我需要一个 Select 报表来汇总每个供应商所拥有的每个不同问题的数量。

select 语句的输出在 table 中看起来像这样:

| Vendor | Defective | Returned | Other |
|--------|-----------|----------|-------|
| Acme   | 1         | 0        | 1     |
| Best   | 1         | 2        | 0     |
| Ace    | 0         | 0        | 2     |

如有任何帮助,我们将不胜感激。

您可以使用 CASE 子句来分隔总和,如:

select
  vendor,
  sum(case when issue = 'Defective' then 1 end) as defective,
  sum(case when issue = 'Returned' then 1 end) as returned,
  sum(case when issue = 'Other' then 1 end) as other
from my_table
group by vendor

最终声明:

$sql = "select
vendor,
sum(case when issue = 'Item Defective' THEN 1 ELSE 0 END) as 'defective',
sum(case when issue = 'Incorrect Item Received' THEN 1 ELSE 0 END) as 'received',
sum(case when issue = 'Incorrect Item Ordered' THEN 1 ELSE 0 END) as 'ordered',
sum(case when issue = 'Item Not Made to Drawing' THEN 1 ELSE 0 END) as 'drawing',
sum(case when issue = 'Other' THEN 1 ELSE 0 END) as 'other'
FROM record GROUP BY vendor";