zfxcms ^回到顶部

您的当前位置:首页 > 最新IT资讯 > mysql行列互换

mysql行列互换

所属分类:   2019-04-09 14:53:02  编辑:admin  浏览次数 518 次

bab407dacc55092f6f1db372171add1.png4bc69b83a71157608a20841e72bb1dd.png72bb121d81f5fd7439bc1ad991c3bfe.png

上面是表

查询每个学生的 每门课程与每门成绩 

select   st.stuid ID ,  st.stunm 姓名, cs.coursenm 课程名 ,sc.scores 成绩 from  student st, score sc ,courses cs

where st.stuid = sc.stuid and sc.courseno = cs.courseno 

a8380ebddb2445d21de451761822735.png

之后我们要把对应的成绩列出来每个人分开,ID对应姓名对应每门课程对应每门成绩(由于高等数学一二没有成绩,最后都为0)

select st.stuid 编号, st.stunm 姓名 ,

Max(case c.coursenm when '大学语文' then s.scores else 0 end ) '大学语文',

max(case c.coursenm when '新视野英语' then IFNULL(s.scores,0)else 0 end) '新视野英语',

Max(case c.coursenm when '离散数学' then IFNULL(s.scores,0) ELSE 0 END) '离散数学',

MAX(case c.coursenm when '概率论与数理统计' then IFNULL(s.scores,0) else 0 end) '概率论与数理统计',

MAX(case c.coursenm  when '线性代数' then IFNULL(s.scores,0) else 0 END) '线性代数',

MAX(case c.coursenm when '高等数学(一)' then IFNULL(s.scores,0) else 0 end) '高等数学(一)',

MAX(case c.coursenm when '高等数学(二)' then IFNULL(s.scores,0) else 0 end) '高等数学(二)'

from  student st 

LEFT JOIN score s on st.stuid = s.stuid

LEFT JOIN courses c on c.courseno = s.courseno

GROUP BY st.stuid

ef8cbe9a20c798c9f7e951cba38017d.png

另外:group_concat()会计算哪些行属于同一组,将属于同一组的列显示出来。要返回哪些列,由函数参数(就是字段名)决定。分组必须有个标准,就是根据group by指定的列进行分组。这个可以很轻松的把数据分出了,最后用foreach循环一下,就能返回对应的数组了,

select   s.stuid 编号 , courseno , s.scores from score s 

image.png

select   s.stuid 编号 , GROUP_CONCAT(courseno) 课程号 , GROUP_CONCAT(s.scores)  成绩  from score s GROUP BY  s.stuid

image.png

随笔文章检索

随笔文章目录