I want to return the top three pets for each employee as columns instead of rows i.e.
Owner_ID Pet
--------------------
1 Cat
1 Dog
1 Hamster
2 Cow
2 Sheep
3 Dog
Convert it to
Owner_ID Pet1 Pet2 Pet3
-------------------------------------
1 Cat Dog Hamster
2 Cow Sheep null
3 Dog null null
The name of pets come from a lookup table and there can be any number of pets but I only want to return the top 3.
Here is my query:
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;
Unfortunately it only returns null for each row... so the output I see is
Owner_ID Pet1 Pet2 Pet3
-------------------------------------
1 null null null
2 null null null
3 null null null
Hopefully it is a common problem and someone must have solved it already.
Thanks