码迷,mamicode.com
首页 > 数据库 > 详细

SQL Server中行列转换

时间:2014-07-19 15:25:24      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   for   

典型实例

一、行转列

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

 

SQL Server中行列转换,布布扣,bubuko.com

SQL Server中行列转换

标签:style   blog   http   color   使用   for   

原文地址:http://www.cnblogs.com/xiaonanmu/p/3854099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!