PIVOT/count列中值的总和-Mysql
我是MYSQL新手,正在尝试获取数据的轴心。我有如下链接的示例表:PIVOT/count列中值的总和-Mysql,mysql,Mysql,我是MYSQL新手,正在尝试获取数据的轴心。我有如下链接的示例表: create temporary table temp(reqtypeid int, reqcode int); insert into temp(reqtypeid, reqcode) values (NULL, 0); insert into temp(reqtypeid, reqcode) values (NULL, 2); insert into temp(reqtypeid, reqcode) values ( 1
create temporary table temp(reqtypeid int, reqcode int);
insert into temp(reqtypeid, reqcode) values (NULL, 0);
insert into temp(reqtypeid, reqcode) values (NULL, 2);
insert into temp(reqtypeid, reqcode) values ( 1 , 0);
insert into temp(reqtypeid, reqcode) values (1 , 1);
insert into temp(reqtypeid, reqcode) values (2 , NULL);
insert into temp(reqtypeid, reqcode) values ( 2 , 0);
insert into temp(reqtypeid, reqcode) values ( 2 , 1);
insert into temp(reqtypeid, reqcode) values ( 3 , 1);
insert into temp(reqtypeid, reqcode) values ( 4 , NULL);
insert into temp(reqtypeid, reqcode) values ( 4 , 1);
我的预期产出是:
我不打算透视,但对于每个reqtypeid,我希望找到reqcode=null、reqcode=0/1/2的计数。我尝试过的代码在链接中。我无法获得正确的输出。有人能帮忙吗?
'NULL'
是字符串文字,与NULL
将任何内容与
NULL
进行比较时,必须使用运算符IS
而不是=
使用如下条件聚合:
SELECT
reqtypeid,
SUM(reqcode IS NULL) reqcode_null,
SUM(reqcode = 0) reqcode_0,
SUM(reqcode = 1) reqcode_1,
SUM(reqcode = 2) reqcode_2
FROM temp
GROUP BY reqtypeid
ORDER BY reqtypeid IS NULL, reqtypeid
请参阅。结果:
考虑应用程序代码中的数据显示问题
> reqtypeid | reqcode_null | reqcode_0 | reqcode_1 | reqcode_2
> --------: | -----------: | --------: | --------: | --------:
> 1 | 0 | 1 | 1 | 0
> 2 | 1 | 1 | 1 | 0
> 3 | 0 | 0 | 1 | 0
> 4 | 1 | 0 | 1 | 0
> null | 0 | 1 | 0 | 1