加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

mssql sqlserver 不固定行转列数据(动态列)

发布时间:2020-12-12 14:19:12 所属栏目:MsSql教程 来源:网络整理
导读:转自:http://www.maomao365.com/?p=5471 摘要: 下文主要讲述动态行列转换语句,列名会根据行数据的不同, 动态的发生变化 ---------------------------------------------------- 实现思路: 主要将待生成的动态列名,采用脚本拼接起来,然后采用pivot函数 运

转自: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,皇冠,10)
insert into #t(compname,霸道,2,30)
insert into #t(compname,3,40)
insert into #t(compname,RAV4,4,60)
insert into #t(compname,5,8)
insert into #t(compname,6,6)
insert into #t(compname,9)
insert into #t(compname,10,10)



/*
 select * from 
 (select compname,daySaleValue,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,chexi from  #t) as d
   pivot(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 t
 while @i <@imax 
 begin
    select @field =field from @fieldList t where t.keyId=@i
    if isnull(@field,‘‘) !=‘‘
     begin
        if @lieMing !=‘‘ begin set @lieMing =@lieMing +, end
        set @lieMing = @lieMing+[+@field+];
     end
    set @i=@i+1
 end
  -------------循环表生成列名end--------------
/*动态组合列*/

set @sql =@sql +@lieMing + ))  t ;;    ---拼接sql语句
exec (@sql)                              ---执行sql脚本,生成相关数据
    
truncate table #t 
drop table #t 

?

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读