sql,行转列

参考链接:https://blog.csdn.net/rainyspring4540/article/details/50231435

t_vehicle表有如下数据:

sql,行转列

 sql初始化语句如下:

-- ----------------------------
-- Table structure for t_vehicle
-- ----------------------------
DROP TABLE IF EXISTS `t_vehicle`;
CREATE TABLE `t_vehicle` (
  `Vehicle_no` varchar(20) DEFAULT NULL,
  `Type` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_vehicle
-- ----------------------------
INSERT INTO `t_vehicle` VALUES (‘粤B11‘, ‘A‘);
INSERT INTO `t_vehicle` VALUES (‘粤B11‘, ‘B‘);
INSERT INTO `t_vehicle` VALUES (‘粤B11‘, ‘B‘);
INSERT INTO `t_vehicle` VALUES (‘粤B22‘, ‘C‘);

现在要实现一个查询,返回结果如下所示:

sql,行转列

这里就涉及到分组查询 ,以及把查询结果的行转换成列的操作,写出来的sql如下:

select
    t.Vehicle_no,
    max(CASE t.Type WHEN ‘A‘ THEN t.ct ELSE 0 END ) A_count,
    max(CASE t.Type WHEN ‘B‘ THEN t.ct ELSE 0 END ) B_count,
    max(CASE t.Type WHEN ‘C‘ THEN t.ct ELSE 0 END ) C_count
from (select Vehicle_no, Type, count(1) ct from t_vehicle group by Vehicle_no, Type)t
group by t.Vehicle_no

注意,这里只考虑到了实现功能,而没有考虑sql的查询性能。

相关推荐