SQL行列转置

时间:2022-07-06 15:48:39
今天给公司同事们出了一道例行考试题,要求写一句SQL语句从上面表转换为下面表,经过艰难思索,一个同事做了出来。
小区             总数    A类车 B类车 C类车
建业森林半岛     210     100    30      80
万科城          200   50    60      90
丰乐园           210      30    70      110

车类型    总数    建业森林半岛 万科城  丰乐园
A类车      180       100       50       30
B类车    160        30       60       70
C类车      280        80       90       110

 
建表
CREATE TABLE `myc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`housing` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`all_car` int(11) DEFAULT NULL,
`a_car` int(11) DEFAULT NULL,
`b_car` int(11) DEFAULT NULL,
`c_car` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of myc
-- ----------------------------
INSERT INTO `myc` VALUES ('1', 'senlinbandao', '210', '100', '30', '80');
INSERT INTO `myc` VALUES ('2', 'wanke', '200', '50', '60', '90');
INSERT INTO `myc` VALUES ('3', 'fengle', '210', '30', '70', '110');
id	housing	       all_car	a_car	b_car	c_car
1 senlinbandao 210 100 30 80
2 wanke 200 50 60 90
3 fengle 210 30 70 110

  

  

 
SQL语句如下:
SELECT

c2 AS '车类型',

IF(c2='A类车',(SELECT SUM(a_car) FROM MYC),IF(c2='B类车',(SELECT SUM(b_car) FROM MYC),IF(c2='C类车',(SELECT SUM(c_car) FROM MYC),0))) AS '总数',

SUM(IF(c1='senlinbandao',c3,0)) AS '建业森林半岛',

SUM(IF(c1='wanke',c3,0)) AS '万科城',

SUM(IF(c1='fengle',c3,0)) AS '丰乐园'
from( select housing as c1,'A类车' as c2,a_car as c3 from MYC
Union select housing,'B类车' as c2,b_car from MYC Union select housing,'C类车' as c2,c_car from MYC
) AS tx group by c2;
第二种写法
SELECT
'a_car' 车类型,
MAX(CASE housing WHEN 'senlinbandao' THEN a_car ELSE 0 END ) 建业森林半岛,
MAX(CASE housing WHEN 'wanke' THEN a_car ELSE 0 END ) 万科城 ,
MAX(CASE housing WHEN 'fengle' THEN a_car ELSE 0 END ) 丰乐园,
SUM(a_car) 总数
FROM myc
UNION
SELECT
'b_car' 车类型,
MAX(CASE housing WHEN 'senlinbandao' THEN b_car ELSE 0 END ) 建业森林半岛,
MAX(CASE housing WHEN 'wanke' THEN b_car ELSE 0 END ) 万科城 ,
MAX(CASE housing WHEN 'fengle' THEN b_car ELSE 0 END ) 丰乐园,
SUM(b_car) 总数
FROM myc
UNION
SELECT
'b_car' 车类型,
MAX(CASE housing WHEN 'senlinbandao' THEN c_car ELSE 0 END ) 建业森林半岛,
MAX(CASE housing WHEN 'wanke' THEN c_car ELSE 0 END ) 万科城 ,
MAX(CASE housing WHEN 'fengle' THEN c_car ELSE 0 END ) 丰乐园,
SUM(c_car) 总数
FROM myc