1

我正在使用这个 SQL 查询

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Animal2) 
                    from animals
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Animal1, ' + @cols + ' from 
             (
                select animal1, animal2, Corelation
                from animals
            ) x
            pivot 
            (
                min(Corelation)
                for animal2 in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

当我执行查询时,我得到一个表作为返回。

如何从该表中进行选择?我尝试使用SELECT * FROM (*past here the script*)但没有用。我只需要将 execute(@query) 的结果用作表并从中进行选择(将其放入新表中)。我该怎么做?

谢谢

注意:该查询是这个 SO question的答案

4

2 回答 2

3

使用Insert into ... exec格式,如下所示:

CREATE TABLE #tmp1 (
   [Animal1] varchar(5), 
   [Cat] decimal(10, 5), 
   [Dog] decimal(10, 5), 
   [Mouse] decimal(10, 5)
)

Insert Into #Tmp1
 execute(@query)  

select * from #tmp1
  where cat = 1

当然,由于列名是动态的,因此您也需要将 create 语句转换为动态 sql。

带有固定版本的 SQL Fiddle

动态版本的 SQL Fiddle

于 2012-10-30T09:36:02.630 回答
2

使用into和一个全局临时表 - 然后您不必提前定义表列。

set @query = 'SELECT Animal1, ' + @cols + 
    +' into ##temp '
    +' from 
             (
                select animal1, animal2, Corelation
                from animals
            ) x
            pivot 
            (
                min(Corelation)
                for animal2 in (' + @cols + ')
            ) p '

select * from ##temp
于 2012-10-30T09:40:31.933 回答