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 2023-09-21 17:27  苏易  阅读(457)  评论(0编辑  收藏  举报

导航