sql query to select records in a specific format (using pivot or other)

橙三吉。 提交于 2020-01-06 04:29:13

问题


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


来源:https://stackoverflow.com/questions/13125187/sql-query-to-select-records-in-a-specific-format-using-pivot-or-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!