选择特定格式记录的sql查询(使用pivot或其他)
我有这样一个SQL表:选择特定格式记录的sql查询(使用pivot或其他),sql,sql-server-2008,pivot,Sql,Sql Server 2008,Pivot,我有这样一个SQL表: Animal1 Animal2 Corelation ---------+---------------+-------------- Cat Cat 1 Cat Dog 0.6 Cat Mouse 0.8 Dog Cat 0.6 Dog
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
use SymbolsDB
select * from [AnimalsTable]
pivot (
[Corelation]
for [Animal2] in (select * from [Animal2]
)
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查询:
Animal 1 Cat Dog Mouse
---------+---------------+------------------+---------------+
Cat 1 0.6 0.8
Dog 6 1 0.4
Mouse 0.8 0.4 1
基本上,我想要更具可读性的表格
我尝试像这样使用pivot:
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
use SymbolsDB
select * from [AnimalsTable]
pivot (
[Corelation]
for [Animal2] in (select * from [Animal2]
)
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)
但它不起作用。我不确定我是否了解pivot是如何工作的,是否可以在我的案例中使用它。还是有别的办法?(我试图避免循环,因为我有100万条记录)
感谢在pivot中,列名必须是常量 为此,需要使用动态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
不能将
SELECT
语句放在PIVOT
中以返回值列表,然后必须为常量。如果您正在寻找一个动态的轴
,那么您将需要使用如下内容:
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
use SymbolsDB
select * from [AnimalsTable]
pivot (
[Corelation]
for [Animal2] in (select * from [Animal2]
)
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)
请参见您是否希望返回所有100万条记录的结果集?(您将有1000个列)