Sql-Server

如何在 PIVOT 內執行 SELECT

  • January 17, 2020

我正在嘗試從數據庫中的列中選擇值,以便對這些值執行 PIVOT 而不對它們進行硬編碼。

SELECT *
FROM (SELECT ItemType, [Status] FROM [EVAULTTEST].[dbo].EvidenceItems WHERE ItemType IS NOT NULL) AS ei

PIVOT(
COUNT([Status])
FOR [Status] 
   IN (SELECT DISTINCT ei.[Status] FROM [EVAULTTEST].[dbo].EvidenceItems AS ei)
) AS piv

然而,我們 IN 裡面的 SELECT 給了我們錯誤:

Incorrect syntax near 'SELECT'. Expecting '.', ID, or QUOTED_ID.

我們如何在 FOR IN 語句中使用 SELECT?

這幾乎就是 bluefeet 在評論中給你的例子。

DECLARE @cols AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME([Status]) 
                   from [EVAULTTEST].[dbo].EvidenceItems
           FOR XML PATH(''), TYPE
           ).value('.', 'NVARCHAR(MAX)') 
       ,1,1,'')

set @query = 'SELECT [ItemType],' + @cols + ' from 
            (SELECT ItemType, [Status]
               from [EVAULTTEST].[dbo].EvidenceItems) x
           pivot 
           (COUNT([Status])
               for [Status] in (' + @cols + ')
           ) p '

execute(@query)

引用自:https://dba.stackexchange.com/questions/106207