使用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;
热门推荐
冬季户外拓展:河南建培教你增强免疫力
北京朝阳医院团队在国际期刊iMeta发表降压药物新机制研究成果
常吃水煮蛋,是养肝还是伤肝?医生提醒:吃鸡蛋要记住4点!
东风村民宿装修大揭秘:土味变时尚!
永靖县东风村民宿:从渔村到网红打卡地的蝶变
左宗棠鸡在家也能做!超简单教程
左宗棠鸡:从清朝到全球的美食传奇
米其林三星餐厅推荐:左宗棠鸡的营养解析
互联网“三家分晋”,蛇年“央晚”有何不同?
拼长方形找质数:北师大版教材的创新教学法
探索100以内质数的秘密:黎曼猜想与哥德巴赫猜想
100以内质数记忆法大揭秘!
meme币的价值共识机制、未来趋势及投资逻辑
区块链技术在供应链管理中的应用:提升透明度与效率
新市古镇羊肉黄酒文化节:一场带动地方经济的文旅盛宴
新市古镇必打卡美食推荐!
冬日打卡新市古镇:羊肉面&茶糕必吃!
成都到重庆自驾游:打卡解放碑和洪崖洞
成都到重庆自驾攻略:理想车主的实用指南
糖尿病患者可以吃西洋参吗?专家解读其功效与注意事项
《十二道锋味》同款:南浔必打卡美食
包玉刚与《我的中国心》:一个时代的共鸣
84平米民宿如何用色彩搭配打造温馨空间
走读合肥:打卡四大历史地标
包公园vs三河古镇:合肥古建双璧,谁主沉浮?
无名的他们,守卫着西南边陲这片中国海
成都到重庆火车票最新攻略:必看!
五天玩遍川渝,打卡乐山大佛和磁器口古镇!
秋冬打卡南浔古镇:百间楼不可错过!
深秋打卡南浔古镇:穿越千年的江南水乡