Pivot-SQL-Werte aus SubQuery

Ich habe eine einfache Frage wie diese ..

USE AdventureWorks;
GO

SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 
FROM Production.Product
GROUP BY DaysToManufacture; 



DaysToManufacture  AverageCost  
0                  5.0885  
1                  223.88  
2                  359.1082  
4                  949.4105  

Ein einfacher Drehpunkt gibt mir

SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,   
[0], [1], [2], [3], [4]  
FROM  
(SELECT DaysToManufacture, StandardCost   
    FROM Production.Product) AS SourceTable  
PIVOT  
(  
AVG(StandardCost)  
FOR DaysToManufacture IN ([0], [1], [2], [3], [4]) 
) AS PivotTable;  

Gibt mir

Cost_Sorted_By_Production_Days   0                     1                     2                     3                     4

AverageCost                    5.0885                223.88                359.1082              NULL                  949.4105

Die Werte in der Pivot-Abfrage sind jedoch Hardcode. Ich möchte diese Werte aus einer Unterabfrage abrufen.

select DaysToManufacture FROM Production.Product GROUP BY DaysToManufacture;

Mit Pivot kann ich jedoch keine Werte aus Unterabfragen abrufen. Gibt es eine andere Möglichkeit, dies zu tun, als eine dynamisch generierte Abfrage zu schreiben?

Antworten auf die Frage(2)

Ihre Antwort auf die Frage