views:

34

answers:

1

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

+2  A: 

If I have understood you correctly you can use ROW_NUMBER() over (partition by Owner_ID order by ...) on your query then pivot using those.

Example follows.

WITH Unpivoted AS
(
SELECT X.*, ROW_NUMBER() over (partition by Owner_ID order by Pet) AS RN
  FROM (VALUES  
(1,        'Cat') , 
(1,        'Dog')  ,
(1,        'Hamster')  ,
(1,        'Rhino'),
(1,        'Zebra'),
(2,        'Cow')  , 
(2,        'Sheep')  ,
(3,        'Dog' ) 
) AS X (Owner_ID, Pet)
)

SELECT Owner_Id, [1] AS Pet1, [2] AS Pet2,[3] AS Pet3 FROM Unpivoted
PIVOT  
(  
Max(Pet)  
FOR RN IN ([1], [2],[3])  
) AS PivotTable; 

Returns

Owner_Id    Pet1    Pet2    Pet3
----------- ------- ------- -------
1           Cat     Dog     Hamster
2           Cow     Sheep   NULL
3           Dog     NULL    NULL
Martin Smith
I had tried the row number earlier but the problem I run into is if a owner has two cats, than I need to get a distinct and with a row number that doesn't work.
sfomate
This helps solve the issue for now, I'll deal with unique sets later.
sfomate