Column value of one table should be column headings when query is executed

51 Views Asked by At

I have two tables: pet type

Id TypeB
1 dog
2 cat
3 snake

Then another owners

Ownerid Pettype
001 1
002 2
003 3
004 0

I am trying to get the values those owners who have pets as in this format

Ownerid Cat Dog snake
001 1 0 0
002 0 1

It should display like this format I tried using joins but couldn’t can any one help me out

I tried using join of three tables

1

There are 1 best solutions below

0
On

use pivot as follows

SELECT *
FROM
(
select Ownerid,TypeB from Ownerstable o
join pettype p
on p.Id=o.Pettype
) d  
PIVOT
(
    count(TypeB)
    FOR TypeB IN ([cat],[dog],[snake])
) p