使用case when,union all实现sql行转列、列转行
创作时间:
作者:
@小白创作中心
使用case when,union all实现sql行转列、列转行
引用
CSDN
1.
https://m.blog.csdn.net/weixin_38653290/article/details/85488532
以前有写过行转列,列转行的博客 具体见:
https://blog.csdn.net/weixin_38653290/article/details/84639754
今天分享下使用case when,union all实现sql行转列、列转行
-- 建表
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;
热门推荐
昆明多家快递企业宣布:春节不打烊!
春节模式已开启,快递"不打烊"方案陆续出炉
田曦薇事件背后的公众人物道德标准探讨
胰腺癌逐渐增多,是甜食吃太多吗?提醒:三个吃饭习惯尽早改
饮食变化与胰腺癌风险探讨
叠纸科技揭秘:《恋与制作人》的情感魔法
《恋与制作人》爆红背后:女性向游戏的成功密码
《难哄》教你用情绪价值征服TA
情绪价值:现代人的养生新选择
雍和宫冬季参拜攻略:如何避开人流高峰?
乾隆皇帝的“龙潜福地”——雍和宫
雍和宫门票预约攻略:手把手教你快速入园
北京雍和宫最新打卡攻略:历史建筑+预约技巧
张大大抑郁康复之路:专业治疗与心理调适双管齐下
张大大事件再升级!律师称其或涉多罪,官媒批“黑红”模式
张大大暴力事件后的道歉与形象重建之路
维生素D2和维生素D3的区别:来源、结构与功效全面解析
生成式AI:重塑人机情感纽带
AI自然语言理解:从技术到应用的全面解析
未来30年全球科技发展重大趋势
探秘恭王府与雍和宫:历史人物大揭秘!
从恭王府到雍和宫:一日游打卡攻略
马未都带你探秘恭王府与雍和宫
如何在测试中保护用户隐私
安徽十大名菜:从臭鳜鱼到中和汤,品味徽州美食文化
二期膜性肾炎的中药治疗
科普|“全能战士” 维生素D
峨眉山:以诗为引,开启一场文化底蕴深厚的旅行
四川峨眉山值得去吗?现在和最近四川峨眉山好吗?
那些年消失的数码产品接口:从3.5mm耳机到PS/2