Reference Links: https://blog.csdn.net/rainyspring4540/article/details/50231435
t_vehicle table has the following data:
sql initialization statement is as follows:
-- ---------------------------- -- 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');
Now to achieve a query and returns the results as follows:
Here involves grouping query, the query result and the line switching operation in a column, the sql written as follows:
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
Note that only considered here to realize the function, without considering the sql query performance.