我有一个简单的查询,像这样。
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
一个简单的枢轴给了我
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;
给我
Cost_Sorted_By_Production_Days 0 1 2 3 4 AverageCost 5.0885 223.88 359.1082 NULL 949.4105
但是数据透视查询中的值是硬编码。我想从子查询中获取这些值。
select DaysToManufacture FROM Production.Product GROUP BY DaysToManufacture;
但是,pivot不允许我从子查询中获取值,除了编写动态生成的查询之外,还有其他方法可以执行此操作吗?
不能。只能使用动态查询来完成。我真的很想知道是否有办法。