I have the following:
DECLARE @tmp TABLE (cid int, pid int, name varchar(10))
Insert Into @tmp (cid, pid, name)
Select 31, 18, 'Pot_One' UNION ALL
Select 32, 18, 'Pot_One' UNION ALL
Select 31, 19, 'Pot_Two' UNION ALL
Select 32, 19, 'Pot_Two' UNION ALL
Select 33, 19, 'Pot_Two' UNION ALL
Select 40, 20, 'Pot_Three'
This describes multiple cid's becoming together to create a pot, for instance 31 and 32 are in pot one and pot id for it is 18, we can have a any number of cid's in a pot (minimum 1 and no max)
What I am trying to achieve is to retrieve pots and relevant cid's in a row, so I thought of using pivot and tried this:
SELECT * from
(
select cid, pid, name
from @tmp
) x
pivot
(
min(cid)
for pid in ([18],[19],[20])
) p
But this returns the following:
name 18 19 20
Pot_One 31 NULL NULL
Pot_Three NULL NULL 40
Pot_Two NULL 31 NULL
Thats is wrong because pot one has 31 and 32 in it and this only represents 31, what I need is potentially:
name 18 18 19 19 19 20
Pot_One 31 32 NULL NULL NULL NULL
Pot_Three NULL NULL NULL NULL NULL 40
Pot_Two NULL NULL 31 32 33 NULL
I have changed the pivot to get the cid's as column headers and got this, which is more closer to what I am trying to achieve:
SELECT * from
(
select cid, pid, name
from @tmp
) x
pivot
(
min(pid)
for cid in ([31],[32],[33],[40])
) p
name 31 32 33 40
Pot_One 18 18 NULL NULL
Pot_Three NULL NULL NULL 20
Pot_Two 19 19 19 NULL
I tried a few different ways without success, are there any other way of achieving this?
Thanks