SQL 服务器数据透视 Table 来自其他 table 的列
SQL server Pivot Table columns from other table
我有这个支点table:
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]
来自另一个 table:
SELECT AFCDIMPI
FROM ANA_IMPIEGHI
问题是:
我可以用子查询替换该列表吗?
谢谢
我认为在这种情况下您应该使用动态查询。下面我举个例子,希望对你有帮助:
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
我有这个支点table:
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]
来自另一个 table:
SELECT AFCDIMPI
FROM ANA_IMPIEGHI
问题是:
我可以用子查询替换该列表吗? 谢谢
我认为在这种情况下您应该使用动态查询。下面我举个例子,希望对你有帮助:
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