0

是否可以从子查询中为 SELECT 查询指定字段名称?例如,我有一个返回数据透视表的查询:

SELECT [Rank], [a], [b], [c], [d], [e], [f], [g], [h]
FROM
(SELECT [File], [Rank], [Piece]
FROM [TableName])
AS [SRC]
PIVOT
(MAX([Piece])
FOR [File]
IN ([a], [b], [c], [d], [e], [f], [g], [h]))
AS [PVT]
ORDER BY [Rank] DESC

所以基本上我需要动态生成这些“[a]、[b]、[c]、[d]、[e]、[f]、[g]、[h]”作为一个来自另一个查询的结果,例如来自某个#TempTable。我想我需要使用某种 Eval() 函数(如果它当然存在的话)?我希望它看起来像这样:

SELECT [Rank], Eval("SELECT ... FROM ...")
FROM
(SELECT [File], [Rank], [Piece]
FROM [TableName])
AS [SRC]
PIVOT
(MAX([Piece])
FOR [File]
IN ( Eval("SELECT ... FROM ...") ))
AS [PVT]
ORDER BY [Rank] DESC
4

1 回答 1

0

感谢 Tobberoth,需要的代码如下所示:

DECLARE @filelist varchar(MAX) =
STUFF(
(SELECT DISTINCT ', [' + [File] + ']'
FROM [#TempTableName]
FOR XML PATH(''))
,1,1,'')

DECLARE @query varchar(MAX) = 
'SELECT [Rank], ' + @filelist + '
FROM
(SELECT [File], [Rank], [Piece]
FROM [TableName])
AS [SRC]
PIVOT
(MAX([Piece])
FOR [File]
IN (' + @filelist + '))
AS [PVT]
ORDER BY [Rank] DESC'

EXECUTE (@query)
于 2015-04-09T11:49:54.433 回答