MySQL解析函数
MySQL Analytic function
我有一个table格式如下
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
我的疑问是,是否可以在一个查询中生成整个输出 table。我正在使用 MySQL DB
请提出您宝贵的建议
您可以使用 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 |
+----------+----------+---------+-----------+---------+--------------+
我有一个table格式如下
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
我的疑问是,是否可以在一个查询中生成整个输出 table。我正在使用 MySQL DB
请提出您宝贵的建议
您可以使用 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 |
+----------+----------+---------+-----------+---------+--------------+