sql query to select records in a specific format (

2019-08-23 05:58发布

问题:

I have an SQL table like this:

Animal1       Animal2       Corelation
---------+---------------+--------------
Cat             Cat           1       
Cat             Dog           0.6     
Cat             Mouse         0.8     
Dog             Cat           0.6 
Dog             Dog           1    
Dog             Mouse         0.4      
Mouse           Cat           0.8     
Mouse           Dog           0.4     
Mouse           Mouse         1   

I'm looking for an SQL query to return the following results:

Animal 1       Cat              Dog               Mouse
---------+---------------+------------------+---------------+
Cat            1                  0.6               0.8
Dog            6                  1                 0.4
Mouse          0.8                0.4               1

Basically i want more readable version of the table.

I tried to use pivot like this:

use SymbolsDB
select * from [AnimalsTable]
pivot (
   [Corelation]
   for [Animal2] in (select * from [Animal2]
)

But it is not working. i am not sure if I understand how the pivot works and if it can be used in my case. Or is there another way to do it? (I am trying to avoid loops because I have 1 million record)

Thanks

回答1:

You cannot place a SELECT statement inside of the PIVOT to return the list of values, then must be constant. If you are looking for a dynamic PIVOT then you will need to use something like this:

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)

See SQL Fiddle with demo



回答2:

In a pivot, the column names must be constant.

So to do this, you need to use dynamic SQL.

declare @options varchar(max) = ''
select @options  = @options + ', [' + animal2 + ']' from (select distinct animal2 from animals) v
select @options = substring(@options ,2, LEN(@options))

declare @sql nvarchar(4000) =
   'select * from [AnimalsTable] pivot (max([Corelation])
   for [Animal2] in (' + @options + ')) p'

   exec sp_executesql @sql