mssql sqlserver 不固定行转列数据(动态列)
原文:mssql sqlserver 不固定行转列数据(动态列)
转自:http://www.maomao365.com/?p=5471
摘要:
下文主要讲述动态行列转换语句,列名会根据行数据的不同,
动态的发生变化
----------------------------------------------------
实现思路:
主要将待生成的动态列名,采用脚本拼接起来,然后采用pivot函数
运行,得到相应的结果
本脚本运行环境:
sql server 2008
/*生成源数据表*/ create table #t (compname varchar(20), cheXi varchar(30), dayInfo int, daySaleValue int)/*生成源数据*/ insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','锐志','1',20) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','皇冠','1',10) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','霸道','2',30) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','锐志','3',40) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','RAV4','4',60) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','锐志','5',8) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','霸道','6',6) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','RAV4','5',9) insert into #t(compname,cheXi,dayInfo,daySaleValue) values('一汽丰田','RAV4','10',10)/*select * from (select compname,daySaleValue,dayInfo,chexi from #t) as d/*注意事项: pivot所涉及的聚合列 value_column 和 pivot_column 都必须存在 上面的查询表中*/pivot(sum(daySaleValue) for dayInfo in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])) t ; */ /*拼接字符串*/ declare @sql varchar(max) set @sql =' select * from (select compname,daySaleValue,dayInfo,chexi from #t) as dpivot(sum(daySaleValue) for dayInfo in( ';/*动态组合列名*/declare @lieMing varchar(7000) ---定义动态生成列名存放变量declare @i int ,@imax int,@field varchar(60) ---定义临时循环变量declare @fieldList table(keyId int identity,field varchar(60)) ---定义临时表,存放待生成动态列名的数据insert into @fieldList(field) select distinct dayInfo from #t ---生成列名数据-------------循环表生成列名start--------------set @lieMing =''set @i=1 select @imax =max(keyId) from @fieldList twhile @i <@imax beginselect @field =field from @fieldList t where t.keyId=@iif isnull(@field,'') !=''beginif @lieMing !='' begin set @lieMing =@lieMing +',' endset @lieMing = @lieMing+'['+@field+']';endset @i=@i+1end-------------循环表生成列名end-------------- /*动态组合列*/set @sql =@sql +@lieMing +' )) t ;'; ---拼接sql语句 exec (@sql) ---执行sql脚本,生成相关数据truncate table #t drop table #t
posted on 2019-03-21 11:27 NET未来之路 阅读(...) 评论(...) 编辑 收藏