sumingyi

mysql横竖表转换

竖表如下:

 

转换为横表

 

-- 横竖表转换 1  多表查询
SELECT c1.name,c1.grade as chinese,c2.grade as math,c3.grade as english from
(SELECT * from stu where course ="语文") c1,
(SELECT * from stu where course ="数学") c2,
(SELECT * from stu where course ="英语") c3
where c1.name=c2.name and c2.name=c3.name and c3.name=c1.name;

 

-- 横竖表转换 2 case...when...then...else...end
select name,
max(case course when "语文" then grade else 0 end ) chinese,
max(case course when "数学" then grade else 0 end ) math,
max(case course when "英语" then grade else 0 end ) english
from stu
group by name;

---- 横竖表转换 3 pivot  SqlServer2005及以上

select * from [Table_A]
pivot(
max([成绩])for [课程]in ([语文],[数学],[英语])
) as 临时表

横表转换为纵表 

1.使用union

2.unpivot  SqlServer2005及以上

select * from [Table_B]
unpivot
(
[成绩] for [课程] in([语文],[数学],[英语])
) as 临时表

posted on   苏易  阅读(480)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示