我有一个像这样的简单查询..
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不允许我从子查询中获取值,除了编写动态生成的查询之外,还有什么方法可以做到这一点吗?
答案 0 :(得分:5)
没有。这只能使用动态查询来完成。我真的很想知道是否有办法。
有些示例使用COALESCE
快速Google search创建列列表。但是,我更喜欢使用STUFF
创建列列表。但是我确实找到了这篇关于使用CTE's and dynamic pivots的文章,这篇文章可能也是赞助的
答案 1 :(得分:1)
要从子查询中获取值,我们可以使用动态查询。我做了一些研究并找到了解决方案。
DECLARE @query VARCHAR(4000)
DECLARE @days VARCHAR(2000)
SELECT @days = STUFF(( SELECT DISTINCT
'],[' + ltrim(str(DaysToManufacture))
FROM Product
ORDER BY '],[' + ltrim(str(DaysToManufacture))
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT ''AverageCost'' AS Cost_Sorted_By_Production_Days,' +
@days +
'FROM (SELECT DaysToManufacture, StandardCost FROM Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN (' + @days + ')) AS PivotTable;'
EXECUTE (@query)