SqlServer2005 行转列,列转行

class表数据

class1表数据


select 
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end)
from
Class
group by [Student]
select 
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end),
[总成绩]=sum([Score]) --加多一列(学科平均分用avg([Score]))
from
Class
group by [Student]

-----以上sql2000 行转列

-----下面sql2005 列转行
select
*
from
Class1
unpivot
([Score] for [Course] in([数学],[物理],[英语],[语文]))b


-----下面sql2005 行转列
select *
from
Class
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b

posted on 2011-12-28 12:03  BarneyZhang  阅读(584)  评论(0编辑  收藏  举报

导航