使用视图中的动态变量创建数据透视表

时间:2019-01-14 22:00:59

标签: sql variables dynamic view pivot

在标题中寻求帮助。当我将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

谢谢!

1 个答案:

答案 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)