姓名 课程 分数
张三 语文 74
张三 数学 83
张三 物理 93
李四 语文 74
李四 数学 84
李四 物理 94
想变成(得到如下结果):
姓名 语文 数学 物理
---- ---- ---- ----
李四 74 84 94
张三 74 83 93
-------------------
创建表:
create table stu_score(
name varchar(20),
cource varchar(20),
score int
);
INSERT INTO stu_score VALUES('zhangsan', '数学', 76);
INSERT INTO stu_score VALUES('zhangsan', '语文', 77);
INSERT INTO stu_score VALUES('zhangsan', '英语', 66);
INSERT INTO stu_score VALUES('lisi', '数学', 45);
INSERT INTO stu_score VALUES('lisi', '语文', 67);
INSERT INTO stu_score VALUES('lisi', '英语', 99);
步骤:
- 按姓名分组,分组查询字段为姓名和最大值
- 在最大值中设置:
- 如果你想查询语文成绩,那么就通过case或者if设置为正常值,将其与的分数设置为0
- 对这个值取sum或者max
3、IF(id='某值',value1,value2)
value1:true时取值
value2:false时取值
4、如果在group by后加上WITH ROLLUP 将会统计出总值。
写法:
SELECT s.name,SUM(IF(s.courcr='数学',score,0)) AS 数学,SUM(IF(s.courcr='语文',score,0)) AS 语文 ,SUM(IF(s.courcr='英语',score,0)) AS 英语 FROM stu_score s GROUP BY s.name;
sql:
SELECT st.true_name,aq.id ,aua.answer_score
FROM assess a
JOIN assess_paper ap ON a.paper_id=ap.id
JOIN assess_question aq ON aq.paper_id=ap.id
JOIN assess_rule_paper arp ON arp.assess_id=a.id
JOIN assess_rule ar ON arp.rule_id=ar.id
JOIN assess_user_answeraua ON aq.id=aua.question_id
JOIN student st ON st.user_id=aua.user_id
JOIN classroom cr ON st.class_id=cr.class_id
JOIN center c ON cr.center_id=c.center_id
JOIN series_class sc ON sc.series_class_name=cr.series_name
结果:
true_nameidanswer_score
冯慧 15
冯慧 24
冯慧 33
冯慧 42
冯慧 51
张瑞雪11
张瑞雪21
张瑞雪31
张瑞雪41
张瑞雪51
杨玉茹13
杨玉茹23
杨玉茹33
杨玉茹43
杨玉茹53
杨月圆14
杨月圆24
杨月圆34
杨月圆44
杨月圆54
罗妃15
罗妃25
罗妃35
罗妃45
罗妃55
唐志琦15
唐志琦25
唐志琦35
唐志琦45
唐志琦55
刘江波15
刘江波25
刘江波35
刘江波45
刘江波55
行转列的sql:
SELECT true_name AS 姓名,
SUM(IF(id='1',answer_score,0)) AS 问题1,
SUM(IF(id='2',answer_score,0)) AS 问题2,
SUM(IF(id='3',answer_score,0)) AS 问题3,
SUM(IF(id='4',answer_score,0)) AS 问题4,
SUM(IF(id='5',answer_score,0)) AS 问题5
FROM (
SELECT st.true_name,aq.id ,aua.answer_score
FROM assess a
JOIN assess_paper ap ON a.paper_id=ap.id
JOIN assess_question aq ON aq.paper_id=ap.id
JOIN assess_rule_paper arp ON arp.assess_id=a.id
JOIN assess_rule ar ON arp.rule_id=ar.id
JOIN assess_user_answeraua ON aq.id=aua.question_id
JOIN student st ON st.user_id=aua.user_id
JOIN classroom cr ON st.class_id=cr.class_id
JOIN center c ON cr.center_id=c.center_id
JOIN series_class sc ON sc.series_class_name=cr.series_name
WHERE ar.rule_name='职业发展顾问的满意度调查php1301'
AND c.center_name='北京亚运村中心'
) wsf
GROUP BY true_name WITH ROLLUP ;
结果: