SQL 行转列===列转行

时间:2021-06-24 17:58:39   收藏:0   阅读:0

 行转列:sum+if

 ======》》

 

SELECT uid,     
sum(if(course=‘语文‘, score, NULL)) as `语文`,

sum(if(course=‘数学‘, score, NULL)) as `数学`,

sum(if(course=‘英语‘, score, NULL)) as `英语`,
sum(if(course=‘物理‘, score, NULL)) as `物理`,
sum(if(course=‘化学‘, score, NULL)) as `化学`
FROM scoreLong GROUP BY uid

其中,if(course=‘语文‘, score, NULL)语句实现了当且仅当课程为语文时取值为课程成绩,否则取值为空,这相当于衍生了一个新的列字段,且对于每个uid而言,其所有成绩就只有特定课程的结果非空,其余均为空。
这样,无论使用任何聚合函数,都可以得到该uid下指定课程的成绩结果。这里是用了sum函数,其实用min、max效果也是一样的,因为待聚合的数值中就只有那一个值非空。


列转行:union

列转行是上述过程的逆过程,所以其思路也比较直观:

=======》》》》

 

SELECT uid, ‘语文‘ as course, `语文` as scoreFROM scoreWideWHERE `语文` IS NOT NULL
UNION
SELECT uid, ‘数学‘ as course, `数学` as scoreFROM scoreWideWHERE `数学` IS NOT NULL
UNION
SELECT uid, ‘英语‘ as course, `英语` as scoreFROM scoreWideWHERE `英语` IS NOT NULL
UNION
SELECT uid, ‘物理‘ as course, `物理` as scoreFROM scoreWideWHERE `物理` IS NOT NULL
UNION
SELECT uid, ‘化学‘ as course, `化学` as scoreFROM scoreWideWHERE `化学` IS NOT NULL
【在每个单门课的衍生表中,例如这句:SELECT uid, ‘语文‘ as course, `语文` as score,用单引号包裹起来的课程名称是字符串常量,比如语文课的衍生表中的课程名都叫语文,然后将该列命名为course;第二个用反引号包裹起来的课程名实际上是从宽表中引用这一列的取值,然后将其命名为score。
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!