MYSQL选择多个不同值的总和
我的桌子看起来像这样:MYSQL选择多个不同值的总和,mysql,select,sum,distinct,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
| 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 |
任何帮助都将不胜感激。您可以使用
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";
谢谢你的帮助。它不起作用。尝试此操作:
$sql=“选择供应商,将sum(问题时案例='Item Defective'然后1 ELSE 0 END)作为'Defective',将sum(问题时案例='error Item Received',然后1 ELSE 0 END)作为'Received',将sum(问题时案例='error Item Ordered',然后1 ELSE 0 END)作为'Ordered',sum(问题时的案例='Item Not Make to Drawing'然后1 ELSE 0 END)为'Drawing',按供应商从记录组中求和(问题时的案例='Other'然后1 ELSE 0 END)为'Other';但这也不起作用。没有错误-什么也不返回。
是否引发错误(哪一个),它是否给了您错误的结果?另外,您不需要案例中的ELSE
。它默认为null
。谢谢!在修复之前删除。现在可以工作了。