[MySQL] 行列转换变化示例

DROP TABLE IF EXISTS  tb;
CREATE TABLE `tb` (
  `cname` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL,
  `cource` varchar(10) DEFAULT NULL,
  `score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO tb VALUES('张三','语文',74);
INSERT INTO tb VALUES('张三','数学',83);
INSERT INTO tb VALUES('张三','物理',93);
INSERT INTO tb VALUES('李四','语文',74);
INSERT INTO tb VALUES('李四','数学',84);
INSERT INTO tb VALUES('李四','物理',94); 
SELECT * FROM tb;

[MySQL] 行列转换变化示例_第1张图片

 


 SELECT cname AS "姓名",
SUM(IF(cource="语文",score,0)) AS "语文",
SUM(IF(cource="数学",score,0)) AS "数学",
SUM(IF(cource="物理",score,0)) AS "物理",
SUM(score) AS "总成绩",
ROUND(AVG(score),2) AS "平均成绩"
FROM tb
GROUP BY cname
UNION ALL
SELECT
"总成绩平均数",
ROUND(AVG(`语文`),2) , ROUND(AVG(`数学`),2), ROUND(AVG(`物理`),2), ROUND(AVG(`总成绩`),2), ROUND(AVG(`平均成绩`),2)
FROM(
SELECT "all",cname AS "姓名",
SUM(IF(cource="语文",score,0)) AS "语文",
SUM(IF(cource="数学",score,0)) AS "数学",
SUM(IF(cource="物理",score,0)) AS "物理",
SUM(score) AS "总成绩",
AVG(score) AS "平均成绩"
FROM tb
GROUP BY cname
)tb2
GROUP BY tb2.all;

结果:[MySQL] 行列转换变化示例_第2张图片

 

转载: [MySQL] 行列转换变化各种方法实现总结(行变列报表统计、列变行数据记录统计等-蒲公英云

你可能感兴趣的:(mysql,数据库,sql)