I have a parent table with two foreign key references to a child table. I am trying to come up with optimal TSQL (SQL Server 2008) that will “pivot” the child column into a row. The table structure and needed result set structure are below. What is the best way to make this work?
Thanks.
set nocount on
declare @parent table ( parentid int , parentword varchar(3) , childid int , childotherid int )
insert into @parent values ( 0 , 'a' , 1 , 3 )
insert into @parent values ( 1 , 'b' , 2 , 4 )
declare @child table ( childid int , childword varchar(3) )
insert into @child values ( 1 , 'ppp' )
insert into @child values ( 2 , 'qqq' )
insert into @child values ( 3 , 'rrr' )
insert into @child values ( 4 , 'sss' )
needed result set
a ppp rrr
b qqq sss
It is not pivoting.Join two times the child table with the parent table.See I have used the left join.If none of childid columns in parent tables are not null.Then you could use the inner join as well.