码迷,mamicode.com
首页 > 数据库 > 详细

SQL竖表转换成横表统计

时间:2019-02-25 12:05:29      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:创建表   The   转换   esc   case   order   sel   else   val   

#创建表user_score
create table user_score
(
    name varchar(20),
    subjects varchar(20),
    score int
);
insert into user_score(name,subjects,score) values('张三','语文',60);
insert into user_score(name,subjects,score) values('张三','数学',70);
insert into user_score(name,subjects,score) values('张三','英语',80);
insert into user_score(name,subjects,score) values('李四','语文',90);
insert into user_score(name,subjects,score) values('李四','数学',100);
#创建表user_score2
create table user_score2
(
    name varchar(20),
    yuwen int,
    shuxue int,
    yingyu int
);
insert into user_score2(name,yuwen,shuxue,yingyu) values('张三',60,70,80);
insert into user_score2(name,yuwen,shuxue,yingyu) values('李四',90,100,0);
#纵表转横表
select name,
sum(case subjects when '语文' then score else 0 end) as '语文',
sum(case subjects when '数学' then score else 0 end) as '数学', 
sum(case subjects when '英语' then score else 0 end) as '英语'
from user_score group by name;
#纵表转横表
SELECT name, 'yuwen' AS subjects, yuwen AS score FROM user_score2 UNION ALL   
SELECT name, 'shuxue' AS subjects, shuxue AS score FROM user_score2 UNION ALL   
SELECT name, 'yingyu' AS subjects, yingyu AS score FROM user_score2  
ORDER BY name,subjects DESC; 

SQL竖表转换成横表统计

标签:创建表   The   转换   esc   case   order   sel   else   val   

原文地址:https://www.cnblogs.com/apollo1616/p/10430087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!