MYSQL选择多个不同值的总和

时间:2019-01-22 19:38:45

标签: mysql select sum distinct

我的桌子看起来像这样:

| 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语句的输出在表中将如下所示:

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:0)

最终声明:

$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";