【网学网提醒】:网学会员编辑为广大网友搜集整理了:SQL语句普通行列转换绩等信息,祝愿广大网友取得需要的信息,参考学习。
/*标题:普通行列转换(version2.0)作者:爱新觉罗.毓华时间:2008-03-09地点:广东深圳说明:普通行列转换(version1.0)仅针对sqlserver2000提供静态和动态写法,version2.0增加sqlserver2005的有关写法。问题:假设有张学生成绩表(tb)如下:课程分数张三语文74张三数学83张三物理93李四语文74李四数学84李四物理94想变成(得到如下结果):语文数学物理---------------李四74张三7484839493
------------------*/
createtabletb(varchar(10),课程varchar(10),分数int)insertintotbvalues('张三','语文',74)insertintotbvalues('张三','数学',83)insertintotbvalues('张三','物理',93)insertintotbvalues('李四','语文',74)insertintotbvalues('李四','数学',84)insertintotbvalues('李四','物理',94)go
--SQLSERVER2005静态SQL。select*from(select*fromtb)apivot(max(分数)for课程in(语文,数学,物理))b
--SQLSERVER2005动态SQL。declare@sqlvarchar(8000)select@sql=isnull(@sql+',','')+课程fromtbgroupby课程exec('select*from(select*fromtb)apivot(max(分数)for课程in('+@sql+'))b')
---------------------------------
/*问题:在上述结果的基础上加平均分,总分,得到如下结果:语文数学物理平均分总分-------------------------李四74张三74*/8483949384.0083.33252250
--SQLSERVER2005静态SQL。selectm.*,n.平均分,n.总分from(select*from(select*fromtb)apivot(max(分数)for课程in(语文,数学,物理))b)m,(select,cast(avg(分数*1.0)asdecimal(18,2))平均分,sum(分数)总分fromtbgroupby)nwherem.=n.--SQLSERVER2005动态SQL。declare@sqlvarchar(8000)select@sql=isnull(@sql+',','')+课程fromtbgroupby课程exec('selectm.*,n.平均分,n.总分from(select*from(select*fromtb)apivot(max(分数)for课程in('+@sql+'))b)m,(select,cast(avg(分数*1.0)asdecimal(18,2))平均分,sum(分数)总分fromtbgroupby)nwherem.=n.')
droptabletb
-----------------------------------
/*问题:如果上述两表互相换一下:即表结构和数据为:语文数学物理张三74李四7483849394
想变成(得到如下结果):课程分数-----------李四语文74李四数学84李四物理94
张三语文74张三数学83张三物理93-------------*/
createtabletb(varchar(10),语文int,数学int,物理int)insertintotbvalues('张三',74,83,93)insertintotbvalues('李四',74,84,94)go
--SQLSERVER2005动态SQL。select,课程,分数fromtbunpivot(分数for课程in([语文],[数学],[物理]))t
--SQLSERVER2005动态SQL,同SQLSERVER2000动态SQL
。
-------------------/*问题:在上述的结果上加个平均分,总分,得到如下结果:课程李四语文李四数学李四物理李四总分张三语文张三数学张三物理张三总分分数
---------------74.0084.0094.00
李四平均分84.00252.0074.0083.0093.00
张三平均分83.33250.00
-----------------*/
select*from(selectas,课程='语文',分数=语文fromtbunionallselectas,课程='数学',分数=数学fromtbunionallselectas,课程='物理',分数=物理fromtbunionall
selectas,课程='平均分',分数=cast((语文+数学+物理)*1.0/3asdecimal(18,2))fromtbunionallselectas,课程='总分',分数=语文+数学+物理fromtb)torderby,case课程when'语文'then1when'数学'then2when'物理'then3when'平均分'then4when'总分'then5end
droptabletb