使用动态SQL语句进行数据透视

使用动态SQL语句进行数据透视,第1张

使用动态SQL语句进行数据透视

您可以使用动态枢轴

create table dbo.test([Name] Varchar(32), Code Varchar(30))insert into dbo.test values   ('A-1', 'A-One'), ('A 2', 'A-Two'), ('B 1-b', 'B-One'), ('B', 'A-Two'), ('C', 'A-One'), ('C', 'B-One'), ('C', 'C-One')declare @cols nvarchar(max)=''  --holds all the values that will become column names declare @alias nvarchar(max)='' --holds values that will become column names and converts values to 'x'declare @sql nvarchar(max)=''   --contains the TSQL dinamically generatedselect @cols = @cols + ', [' + [Name] + ']' from dbo.test group by [Name]select @alias = @alias + ', case when T.[' + [Name] + '] is not null then ''x'' else '''' end as [' + [Name] + ']'from dbo.test group by [Name]set @cols = RIGHt(@cols, len(@cols)-2) set @sql = @sql + ' select  T.Code ' + @alias + ' from ('set @sql = @sql + ' select piv.[Code], ' + @cols set @sql = @sql + ' from dbo.test ' set @sql = @sql + ' pivot (max([Name]) for [Name] in ('+@cols+') ) piv ' set @sql = @sql + ' ) T'--execute dynamic queryexec(@sql)

结果:



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5640837.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存