MySql row to column, column to row example 1

 

Go directly to the code, the first is to build a test table

Test data source:  https://www.cnblogs.com/linJie1930906722/p/6036714.html

--建表语句
CREATE  TABLE StudentScores
(
   UserName         NVARCHAR(20),        
   SubjectName          NVARCHAR(30),        
   Score            FLOAT             
)

--插入数据
INSERT INTO StudentScores SELECT '张三', '语文', 80;
INSERT INTO StudentScores SELECT '张三', '数学', 90;
INSERT INTO StudentScores SELECT '张三', '英语', 70;
INSERT INTO StudentScores SELECT '张三', '生物', 85;
INSERT INTO StudentScores SELECT '李四', '语文', 80;
INSERT INTO StudentScores SELECT '李四', '数学', 92;
INSERT INTO StudentScores SELECT '李四', '英语', 76;
INSERT INTO StudentScores SELECT '李四', '生物', 88;
INSERT INTO StudentScores SELECT '码农', '语文', 60;
INSERT INTO StudentScores SELECT '码农', '数学', 82;
INSERT INTO StudentScores SELECT '码农', '英语', 96;
INSERT INTO StudentScores SELECT '码农', '生物', 78;

--查一下是否插入成功
select * from studentscores;

 

--先做基础的sql查询

select b.username , c.语文,d.数学,e.英语,f.生物 ,g.总分 from 
		(select a.UserName from studentscores a GROUP BY UserName) b ,
		(SELECT s.USERNAME , s.SCORE 语文 FROM studentscores  s  where s.subjectName = '语文')c,
		(SELECT s.USERNAME , s.SCORE 数学 FROM studentscores  s  where s.subjectName = '数学')d ,
		(SELECT s.USERNAME , s.SCORE 英语 FROM studentscores  s  where s.subjectName = '英语')e,
		(SELECT s.USERNAME , s.SCORE 生物 FROM studentscores  s  where s.subjectName = '生物')f ,
			(SELECT  s.username ,sum(s.score) 总分  from studentscores s GROUP BY s.username) g	
				where  b.UserName = c.USERNAME and c.USERNAME = d.USERNAME and d.USERNAME = e.USERNAME and e.USERNAME = f.USERNAME and f.USERNAME=g.username ;

 

 

--带函数的高级一些的语句

SELECT UserName,
 MAX(
 CASE
 WHEN subjectName='语文'
 THEN score
 ELSE 0
 END) AS "语文",
 MAX(
 CASE
 WHEN subjectName='数学'
 THEN score
 ELSE 0
 END) AS "数学",
 MAX(
 CASE
 WHEN subjectName='英语'
 THEN score
 ELSE 0
 END) AS "英语",
 MAX(
 CASE
 WHEN subjectName='生物'
 THEN score
 ELSE 0
 END) AS "生物" ,
 sum(score) AS "总分"
FROM studentscores
GROUP BY UserName

The effect is the same.

 

 

 

 

Published 22 original articles · Like 3 · Visitor 3442

Guess you like

Origin blog.csdn.net/ChyoD1811/article/details/99293824