首页 > 开发 > 综合 > 正文

讲解数据库中行级转换成列级的实际应用

2024-07-21 02:42:01
字体:
来源:转载
供稿:网友
讲解数据库中行级转换成列级的实际应用:

首先,我们需要建立一个表,详细内容请参考下文:

create table score(   Name    varchar(10),   Subject varchar(10),   Result int)go -- Insert some data to score tableinsert into score(Name , Subject , Result) values('Jason' , 'Chinese' , 74)insert into score(Name , Subject , Result) values('Jason' , 'Math' , 83)insert into score(Name , Subject , Result) values('Jason' , 'Physic' , 93)insert into score(Name , Subject , Result) values('Bosco' , 'Chinese' , 74)insert into score(Name , Subject , Result) values('Bosco' , 'Math' , 84)insert into score(Name , Subject , Result) values('Bosco' , 'Physic' , 94)go -- useing PIVOT OperatorSELECT * FROM(        select Name,Subject,Result from score) as XPIVOT(       Sum(Result) FOR Subject IN ([Chinese],[Math],[Physic])) AS PVT -- useing static SQL. There only are [Chinese],[Math],[Physic] values in subject fieldselect Name, sum(case Subject when 'Chinese' then Result else 0 end) as [Chinese], sum(case Subject when 'Math' then Result else 0 end) as [Math], sum(case Subject when 'Physic' then Result else 0 end) as [Physic]from scoregroup by Name -- useing dynamic SQL. There may be some other values in subject field,don't limited to [Chinese],[Math],[Physic]declare @sql varchar(2000)set @sql = 'select Name'select @sql = @sql + ', sum(case Subject when ''' + Subject + ''' then Result else 0 end) [' + Subject + ']'from (select distinct Subject from score) as Xset @sql = @sql + ' from score group by Name'exec(@sql)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表