从Pivot查询创建表

时间:2018-02-02 07:49:35

标签: sql sql-server

我正在尝试从以下数据透视表创建一个表:

Declare @t VARCHAR(10)
Declare @A VARCHAR(1000)
Declare @B VARCHAR(1000)
set @A='SELECT SUBURB, Campaign_date, [Type] '
SET @B='('


SELECT @A=@A+',['+Weeks+'] as [' +Weeks+']',@B=@B+'['+Weeks+'],' FROM (SELECT DISTINCT Weeks FROM [tbl_FTTH_OrdersIn_SummerCamp]) cur
-- removing last ',' from both variables
SET @B=SUBSTRING(@B,1,LEN(@B)-1)
SET @A=@A+ + ' FROM (SELECT [NAME]
      ,[TOWN]
      ,[SUBURB], [Weeks], [count], Campaign_date, [Type] FROM [dbo].[tbl_FTTH_OrdersIn_SummerCamp]) s  PIVOT (sum(Count) FOR weeks IN ' +@B+')) p ORDER BY suburb';
exec(@A);

我该怎么做?

查询运行正常并返回结果。

1 个答案:

答案 0 :(得分:0)

INTO有一个条款:

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;