我有一张格式低于表格的表
SurveyCity ProductName SurveybyCompany1 SurveybyCompany2
City1 Chocolate Good Good
City1 Caramel Good Bad
City1 Vanilla Bad Good
City1 Butterscoth Bad Bad
City2 Chocolate Good Good
City2 Caramel Good Bad
City2 Vanilla Bad Good
City2 Butterscoth Bad Bad
我想要一份这样的报告
Company1 Company2 Caramel Chocolate Vanilla Butterscoth
Good Good 0 2 0 0
Good Bad 2 0 0 0
Bad Good 0 0 2 0
Bad Bad 0 0 0 2
我正在写下面的4个查询来生成此报告
select productname,count(*) from table where surveybycompany1='Good' and surveybycompany2='Good' group by productname
我的疑问是,是否可以在一个查询中生成整个输出表。我正在使用MySQL DB
请提供您宝贵的建议
答案 0 :(得分:2)
您可以使用sum
,if
和group by
select SurveybyCompany1 Company1,
SurveybyCompany2 Company2,
sum(if(ProductName = 'Caramel', 1, 0)) as Caramel,
sum(if(ProductName = 'Chocolate', 1, 0)) as Chocolate,
sum(if(ProductName = 'Vanilla', 1, 0)) Vanilla,
sum(if(ProductName = 'Butterscoth', 1, 0)) Butterschoth
from your_table group by Company1, Company2
order by Company1 desc, Company2 desc;
输出:
+----------+----------+---------+-----------+---------+--------------+
| Company1 | Company2 | Caramel | Chocolate | Vanilla | Butterschoth |
+----------+----------+---------+-----------+---------+--------------+
| Good | Good | 0 | 2 | 0 | 0 |
| Good | Bad | 2 | 0 | 0 | 0 |
| Bad | Good | 0 | 0 | 2 | 0 |
| Bad | Bad | 0 | 0 | 0 | 2 |
+----------+----------+---------+-----------+---------+--------------+