SQL Server中行列转换

典型实例

一、行转列

1、建立表格

ifobject_id('tb')isnotnulldroptabletb

go

createtabletb(姓名varchar(10),课程varchar(10),分数int)

insertintotbvalues('张三','语文',74)

insertintotbvalues('张三','数学',83)

insertintotbvalues('张三','物理',93)

insertintotbvalues('李四','语文',74)

insertintotbvalues('李四','数学',84)

insertintotbvalues('李四','物理',94)

go

select*fromtb

go

姓名       课程       分数

---------- ---------- -----------

张三       语文        74

张三       数学        83

张三       物理        93

李四       语文        74

李四       数学        84

李四       物理        94

 

 

使用SQL Server 2000静态SQL

 

select姓名,

 

max(case课程when'语文'then分数else0end)语文,

 

max(case课程when'数学'then分数else0end)数学,

 

max(case课程when'物理'then分数else0end)物理,

 

sum(分数)总分,

 

cast(avg(分数*1.0)asdecimal(18,2))平均分

 

fromtb

 

groupby姓名

 

 

 

使用SQL Server 2005静态SQL

 

selectm.*,n.总分,n.平均分

 

from

 

(select*fromtb pivot(max(分数)for课程in(语文,数学,物理))a)m,

 

(select姓名,sum(分数)总分,cast(avg(分数*1.0)asdecimal(18,2))平均分

 

fromtb

 

groupby姓名)n

 

wherem.姓名=n.姓名

 

 

 

引用:http://www.cnblogs.com/zhangzt/archive/2010/07/29/1787825.html

 

posted @ 2014-07-18 18:16  H辉  阅读(396)  评论(0编辑  收藏  举报