mysql 行转列
来源:互联网 发布:github for windows 编辑:程序博客网 时间:2024/05/18 00:02
1.准备表和数据
CREATE TABLE test_user ( name varchar(50) DEFAULT NULL, subject varchar(50) DEFAULT NULL, score int(11) DEFAULT NULL);insert into test_user values('zhangsan' , 'chinese' , 10),('zhangsan' , 'math' , 20),('zhangsan' , 'english' , 30),('lily' , 'chinese' , 40),('lily' , 'math' , 50),('lily' , 'english' , 60),('mini' , 'chinese' , 70),('mini' , 'math' , 80),('mini' , 'english' , 90);效果图
2.行转列
select name, max(IF(subject = 'chinese',score,0)) as 'chinese', max(IF(subject = 'math',score,0)) as 'math', max(IF(subject = 'english',score,0)) as 'english', sum(score) as'total'from test_usergroup by name
IF(subject = 'chinese',score,0),指定列的值,若,是指定列,则列的值为score或者0,所以,会有max函数的出现
max(),最大值,根据分组,会出现三条数据,当前score的分数、0、0,使用max函数,则匹配到需求数据
tips:
此种方法,需要提前知道列名,有一定局限性。如果需要套公式的效果,则可能需要存储过程,一条sql可能搞不定
0 0
- mysql 行转列
- mysql 行转列
- MySQL行转列
- mysql 行转列
- Mysql 行转列
- Mysql行转列
- mysql 行转列
- mysql 行转列
- mysql 行转列
- mysql 行转列
- Mysql 行转列
- mysql 行转列
- mysql 行转列
- mysql 行转列
- mysql 行转列
- Mysql行转列
- mysql行转列
- mysql 行转列
- 【规范】JNDI
- 数据集 DataRow.RowState 属性深入分析
- 数据结构-3
- sock_stream与sock_dgram的区别
- Lua debug library
- mysql 行转列
- 通讯相关知识
- 如何控制navigationbar透明
- 过时date.toLocaleString()的解决方法
- Missing iOS Distribution signing identity for *****问题解决
- iOS9网络适配_改用更安全的HTTPS
- android WebView开发总结<续>
- 【bzoj2127】happiness 最小割
- 关于new 和delete的灾祸