为了阅读方便,现在需要将查询出来多条数据转换为单行数据,现在可以使用CASE WHEN
的方法转换为单行数据。
数据表
CREATE TABLE `device_info` (
`id` int(11) NOT NULL,
`resource_type` int(2) DEFAULT NULL COMMENT '类型',
`device_code` varchar(255) DEFAULT NULL COMMENT '编码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
其中类型值有1,2两种类型,device_code设备编码有多种,现在想实现,统计每个设备编码有多少种类型1的数据,有多少种类型2 的统计数据。
数据
id | resource_type | device_code |
---|---|---|
1 | 2 | A1101 |
2 | 2 | A1101 |
3 | 1 | A2001 |
4 | 2 | A2001 |
5 | 1 | A2001 |
6 | 1 | A1101 |
SQL实现
select
device_code,
SUM(CASE WHEN resource_type = 1 THEN 1 ELSE 0 END) AS type1,
SUM(CASE WHEN resource_type = 2 THEN 1 ELSE 0 END) AS type2
from device_info group by device_code
结果
device_code | type1 | type2 |
---|---|---|
A1101 | 1 | 2 |
A2001 | 2 | 1 |
实现思路
先通过设备编码进行分组,然后使用CASE WHEN
的方法,如果是类型1则设为1
,然后其他值就是0
,这样使用sum
方法跟count(id) ...where resource_type = 1
是一样的效果,这样就实现多行转单行的效果,阅读就比较方便!