如果您查看 Mikael 链接的答案,您会意识到您需要动态地为您的数据透视语句构建列,因为 PIVOT 语法不允许在 FOR 子句中进行子选择。所以基本上你需要做这样的事情:
DECLARE
@cols AS NVARCHAR(MAX),
@y AS INT,
@sql AS NVARCHAR(MAX);
-- Construct the column list for the IN clause
-- e.g., [Urea],[Uric Acid],[Cholesterol]
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT (LabTestName) AS y FROM YourTable) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
您现在可以像这样构建您的 PIVOT 语句:
set @SQL = N'
SELECT SourceCollectedDate,'+@cols+N'
FROM YourTable
PIVOT (
SUM(results) FOR LabTestName IN ( '+@cols+N')
) AS PivotTable
ORDER BY SourceCollectedDate desc
'
并执行它:
EXEC sp_executesql @sql
这将产生:
SourceCollectedDate Urea Uric Acid Cholesterol
2013-06-04 00:00:00.000 5 10 NULL
2013-06-03 00:00:00.000 NULL NULL 25
请注意,我的示例具有YourTable
表名。您需要将其替换为您的实际表名。
SQL Fiddle(基于 Chad 创建的内容)