将pivot sql结果放入临时表的方法

时间:2013-01-17 06:36:53

标签: sql sql-server pivot pivot-table

在sql server上工作。写一个关键的sql,下面是我的表和关键的sql语法 .MY问题无法将这个关键值放在Temp表中。

-----------------Table-1-------------
CREATE TABLE Table1 (ColId INT,ColName VARCHAR(10))
INSERT INTO Table1 VALUES(1, 'Country')
INSERT INTO Table1 VALUES(2, 'MONTH')
INSERT INTO Table1 VALUES(3, 'Day')



----------------Table-2----------------------------

CREATE TABLE Table2 (tID INT,ColID INT,Txt VARCHAR(10))

INSERT INTO Table2 VALUES (1,1, 'US')
INSERT INTO Table2 VALUES (1,2, 'July')
INSERT INTO Table2 VALUES (1,3, '4')
INSERT INTO Table2 VALUES (2,1, 'US')
INSERT INTO Table2 VALUES (2,2, 'Sep')
INSERT INTO Table2 VALUES (2,3, '11')
INSERT INTO Table2 VALUES (3,1, 'US')
INSERT INTO Table2 VALUES (3,2, 'Dec')
INSERT INTO Table2 VALUES (3,3, '25')


--------------
----------------Pivotal sql----------------------------

DECLARE @query NVARCHAR(4000)
DECLARE @cols NVARCHAR(2000)

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t2.ColName
                        FROM    Table1 AS t2
                        ORDER BY '],[' + t2.ColName
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'                    

SET @query = N'SELECT tID, '+
@cols +'
FROM
(SELECT  t2.tID
      , t1.ColName
      , t2.Txt 
FROM    Table1 AS t1
        JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
@cols +' )
) AS pvt
ORDER BY tID;'
EXECUTE(@query)

执行bellow命令之后想要将此值用于其余工作,所以我需要将此命令结果值放在临时表中

 EXECUTE(@query)

2 个答案:

答案 0 :(得分:0)

试试这个:

Declare @Sample table
(
 tID int,
 Country VARCHAR(10),
 Day int ,
 MONTH  VARCHAR(10)
)

Insert into @Sample 
EXECUTE(@query)

select * from @Sample

以同样的方式,您可以创建temp table而不是table variable并将其插入其中

答案 1 :(得分:0)

如果你能够通过使用EXECUTE(@Querys)来完成剩下的程序,你可以做类似的事情

Declare @TabName Varchar(40)

Select @TabName='##'+Replace(CAST(NEWID() as Varchar(40)),'-','')

DECLARE @query NVARCHAR(4000)
DECLARE @cols NVARCHAR(2000)

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t2.ColName
                        FROM    Table1 AS t2
                        ORDER BY '],[' + t2.ColName
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'                    

SET @query = N'SELECT tID, '+
@cols +' into ' +@TabName + '
FROM
(SELECT  t2.tID
      , t1.ColName
      , t2.Txt 
FROM    Table1 AS t1
        JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
@cols +' )
) AS pvt
ORDER BY tID;'

Print @Query
EXECUTE(@query)

Select @query = 'Select * from ' + @Tabname
EXECUTE(@query)

Select @query = 'Drop Table ' + @Tabname
EXECUTE(@query)

如果您不想这样做,可以使用“硬”## temptable,但是您无法在多用户环境中使用此保存。