SQL Server纵表与横表相互转换的方法
程序员文章站
2024-01-02 14:08:46
1,纵表转横表
纵表结构 table_a:
转换后的结构:
纵表转横表的sql示例:
select name ,
sum(case...
1,纵表转横表
纵表结构 table_a:
转换后的结构:
纵表转横表的sql示例:
select name , sum(case when course = n'语文' then grade else 0 end) as chinese , sum(case when course = n'数学' then grade else 0 end) as mathematics , sum(case when course = n'英语' then grade else 0 end) as english from dbo.table_a group by name
2,横表转纵表
横表结构table_b:
转换后的表结构:
横表转纵表的sql示例:
select name , 'chinese' as course , chinese as score from dbo.table_b union all select name , 'mathematics' as course , mathematics as score from dbo.table_b union all select name , 'english' as course , english as score from dbo.table_b order by name , course desc
以上所述是小编给大家介绍的sql server纵表与横表相互转换的实现方法,希望对大家有所帮助