行转列、列转行

--  建表
CREATE  TABLE StudentScores
(
   UserName         NVARCHAR(20),        -- 学生姓名
   Subject          NVARCHAR(30),        -- 科目
   Score            FLOAT               -- 成绩
)
-- 添加数据
INSERT INTO StudentScores SELECT '张三', '语文', 80 ;
INSERT INTO StudentScores SELECT '张三', '数学', 90 ;
INSERT INTO StudentScores SELECT '张三', '英语', 70 ;
INSERT INTO StudentScores SELECT '张三', '生物', 85 ;
INSERT INTO StudentScores SELECT '李四', '语文', 80 ;
INSERT INTO StudentScores SELECT '李四', '数学', 92 ;
INSERT INTO StudentScores SELECT '李四', '英语', 76 ;
INSERT INTO StudentScores SELECT '李四', '生物', 88 ;
INSERT INTO StudentScores SELECT '码农', '语文', 60 ;
INSERT INTO StudentScores SELECT '码农', '数学', 82 ;
INSERT INTO StudentScores SELECT '码农', '英语', 96 ;
INSERT INTO StudentScores SELECT '码农', '生物', 78 ;

插入数据后,如下:

-- 使用PIVOT行转列
SELECT * FROM StudentScores 
AS P
PIVOT 
(
    SUM(Score) FOR 
    p.Subject IN ('语文','数学','英语','生物')
) AS T

--  使用case when行转列
select UserName,
       max(case when subject='语文' then score else 0 end) 语文,
       max(case when subject='数学' then score else 0 end) 数学,
	   max(case when subject='英语' then score else 0 end) 英语,
	   max(case when subject='生物' then score else 0 end) 生物
from StudentScores
group by UserName

 行转列后如下:

 列转行:

-- 建表
drop table if exists StudentScores2;
CREATE  TABLE StudentScores2
(
   UserName         NVARCHAR(20),        -- 学生姓名
   语文             FLOAT,        -- 科目
   数学             FLOAT,        -- 科目
   英语             FLOAT,        -- 科目
   生物             FLOAT        -- 科目
);

-- 添加数据
insert into StudentScores2
 select UserName,
       max(case when subject='语文' then score else 0 end) 语文,
       max(case when subject='数学' then score else 0 end) 数学,
	   max(case when subject='英语' then score else 0 end) 英语,
	   max(case when subject='生物' then score else 0 end) 生物
from StudentScores
group by UserName;

-- 使用union all 列转行

select UserName,'语文' subject,语文 score
from StudentScores2
union all
select UserName,'数学' subject,数学 score
from StudentScores2
union all
select UserName,'英语' subject,英语 score
from StudentScores2
union all
select UserName,'生物' subject,生物 score
from StudentScores2;

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值