我要爲列而非行即透視SQL Server上2010
Owner_ID Pet
--------------------
1 Cat
1 Dog
1 Hamster
2 Cow
2 Sheep
3 Dog
將它轉換爲每個員工返回前三名寵物
Owner_ID Pet1 Pet2 Pet3
-------------------------------------
1 Cat Dog Hamster
2 Cow Sheep null
3 Dog null null
寵物的名字來自查找表可以有任意數量的寵物但我只想返回前三名。
這是我的查詢:
SELECT Owner,Pet1, Pet2,Pet3
FROM
(select distinct OwnerID as Owner,glcom.Value as Pets
from Owner ,OwnerPets ,Pet
where Pet.Type='Furry'
and OwnerPets.OwnerID = OwnerID.OwnerID
and OwnerPets.PetID = Pet.PetID) AS SourceTable
PIVOT
(
Max(Pets)
FOR Pets IN (Pet1, Pet2,Pet3)
) AS PivotTable;
遺憾的是它只爲每一行返回null ...所以我看到的輸出是
Owner_ID Pet1 Pet2 Pet3
-------------------------------------
1 null null null
2 null null null
3 null null null
希望這是一個普遍的問題,必須有人已經解決了它。
感謝
跆拳道是SQL Server 2010的?最新版本是2008 R2。 – 2010-06-24 22:48:08
注意:我的答案假設您在跟蹤Brent Ozar調用2008 R2 SQL Server 2010! http://www.brentozar.com/archive/2009/02/sql-server-2010-features-leaked/ – 2010-06-25 08:36:21
:)是的,它的確如此。 – sfomate 2010-06-28 16:28:29