[英]sql query to select records in a specific format (using pivot or other)
我有一個像這樣的SQL表:
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
我正在尋找一個SQL查詢來返回以下結果:
Animal 1 Cat Dog Mouse
---------+---------------+------------------+---------------+
Cat 1 0.6 0.8
Dog 6 1 0.4
Mouse 0.8 0.4 1
基本上我想要更可讀的表格版本。
我嘗試使用這樣的樞軸:
use SymbolsDB
select * from [AnimalsTable]
pivot (
[Corelation]
for [Animal2] in (select * from [Animal2]
)
但它沒有用。 我不確定我是否理解樞軸是如何工作的,以及它是否可以在我的情況下使用。 或者還有另一種方法嗎? (我試圖避免循環,因為我有100萬條記錄)
謝謝
您不能在PIVOT
內部放置SELECT
語句以返回值列表,然后必須是常量。 如果您正在尋找動態PIVOT
那么您將需要使用以下內容:
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。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.