其他表中的SQL Server Pivot Table列

时间:2015-06-19 14:48:55

标签: sql sql-server sql-server-2008 tsql pivot-table

我有这个数据透视表:

Property

列表:select * from TEST_COUNT_LINE_IMP pivot (SUM (COUNT_CICLI) for Impiego in ([AT],[CL],[PD],[PR],[RC],[RW],[RV],[SP],[TR],[PV],[ST])) as T1 来自另一张桌子:

[AT],[CL],[PD],[PR],[RC],[RW],[RV],[SP],[TR],[PV],[ST]

问题是:

我可以用子查询替换该列表吗? 感谢

1 个答案:

答案 0 :(得分:2)

我认为在这种情况下你应该使用动态查询。我在下面有一个例子,希望它能帮到你:

DECLARE @statement NVARCHAR(max)
,@columns NVARCHAR(max)

SELECT @columns = ISNULL(@columns + ', ', '') + '[' + tbl.ColName + ']'
FROM (
   SELECT DISTINCT ColName
   FROM TableName
   ) AS tbl

SELECT @statement = ' SELECT * FROM TableName as tbl PIVOT (MAX(tbl.VALUE) for tbl.ColName in (' + @columns + ')) as pvt'

EXEC sp_executesql @statement = @statement