MYSQL Выберите сумму нескольких различных значений - PullRequest
0 голосов
/ 22 января 2019

Мой стол выглядит так:

| 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 голосов
/ 22 января 2019

Окончательное утверждение:

$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";
0 голосов
/ 22 января 2019

Вы можете использовать предложение 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
...