美文网首页
SQL行转列,列转行练习

SQL行转列,列转行练习

作者: peerben | 来源:发表于2019-03-24 10:29 被阅读0次
l59725c7b68eee5110221ab809aa58a9b-speerben6168405538415827955-mb7d849a0573641f822833ee11e7206c0.jpg
SELECT sn.name,
       MAX(IF(stu.course = 'mysql', stu.score, null)) AS MYSQL,
       MAX(IF(stu.course = 'JAVA', stu.score, null)) AS JAVA
FROM stdscore sn
INNER JOIN stdscore stu ON sn.name = stu.name
GROUP BY sn.name
CREATE VIEW stuscore AS
SELECT sn.name,
       MAX(IF(stu.course = 'mysql', stu.score, null)) AS MYSQL,
       MAX(IF(stu.course = 'JAVA', stu.score, null)) AS JAVA
FROM stdscore sn
INNER JOIN stdscore stu ON sn.name = stu.name
GROUP BY sn.name;

SELECT * FROM stuscore;
SELECT * FROM stdscore;

SELECT  * FROM (SELECT s.name, 'mysql' as course, s.MYSQL as score FROM stuscore s
UNION ALL
SELECT s2.name, 'JAVA' as course, s2.JAVA as score FROM stuscore s2) as stu
ORDER BY stu.name desc ;

相关文章

网友评论

      本文标题:SQL行转列,列转行练习

      本文链接:https://www.haomeiwen.com/subject/hwpyvqtx.html