在标题中寻求帮助。当我将Scenario1硬编码为“ ACT”时,数据透视表的工作方式如“ Script1” 所示。 “ Script2” 是我尝试对其进行动态设置(当然不起作用)。任何帮助表示赞赏!
SCRIPT1
SELECT year, GRP_LEVEL, ACT FROM (SELECT Scenario1, year, GRP_LEVEL, TotalAmount FROM [dbo].[VW_exp_by_dept1]) b PIVOT (SUM (TotalAmount) FOR Scenario1 IN (ACT)) piv GROUP BY year, GRP_LEVEL, ACT --ORDER BY GRP_LEVEL GO
“ SCRIPT2”
DECLARE @ScenarioA AS varchar (50); SET @ScenarioA = 'ACT'; ( SELECT year, GRP_LEVEL, @ScenarioA FROM (SELECT Scenario1, year, GRP_LEVEL, TotalAmount FROM [dbo].[VW_exp_by_dept1]) b PIVOT (SUM (TotalAmount) FOR Scenario1 IN (@ScenarioA)) piv ) GROUP BY year, GRP_LEVEL, ScnearioA --ORDER BY GRP_LEVEL GO
谢谢!
答案 0 :(得分:0)
一种可能是使用动态SQL。您构建一个包含SQL查询的字符串并将其执行。一个例子是:
DECLARE @ScenarioA AS varchar (50);
DECLARE @DynamicQuery as varchar(MAX);
SET @ScenarioA = 'ACT';
SET @DynamicQuery = '
SELECT
year,
GRP_LEVEL,'
+ CAST(@ScenarioA as varchar) + '
FROM
(SELECT
Scenario1,
year,
GRP_LEVEL,
TotalAmount
FROM
[dbo].[VW_exp_by_dept1]) b
PIVOT
(SUM (TotalAmount) FOR Scenario1 IN (' + CAST(@ScenarioA as varchar) + ')) piv
GROUP BY
year,
GRP_LEVEL, '
+ CAST(@ScenarioA as varchar) + '
--ORDER BY GRP_LEVEL'
EXEC(@DynamicQuery)