Click here to Skip to main content
15,885,811 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to join two tables data and want these data in a single row
e.g.
Table Parent
Pid Pname Pemail
1 Sumit sy@ymail.com
2 Neeraj nl@gmail.com
3 Manish m@gmail.com

Table Child
Cid Cname Pid
1 sonu 1
2 bhikhu 2
3 chintu 3
4 dhiraj 2
5 monu 2
6 monika 3

i used query below
SQL
select parent.Pid,parent.Pname,parent.Pemail,child.Cname
from parent right outer join child
ON parent.Pid= child.Pid
where parent.Pid=2


and got result below
Pid Pname Pemail Cname
2 Neeraj nl@gmail.com bhikhu
2 Neeraj nl@gmail.com dhiraj
2 Neeraj nl@gmail.com monu

But i want it in this format
Pid Pname Pemail Cname1 Cname2 Cname3
2 Neeraj nl@gmail.com bhikhu dhiraj monu

Please Help.
Posted
Updated 9-Jan-13 5:01am
v2
Comments
willempipi 9-Jan-13 11:14am    
I'm really curious about the correct answer to this question. My solution (if it would be required to be in SQL) would be to first query the maximum amount of children per parent, than create a temporary table with the amount of columns, than use a cursor to fill the temporary table.

SQL
select *
from
(
  select val, Cid,Item
  from child
  unpivot
  (
    val
    for Item in (Cname)
  )u
) x
pivot
(
  max(val)
  for Cid in ([1], [2], [3], [4], [5], [6],[7], [8], [9], [10], [11], [12],[13])
) p



and for Help check this link [^]
 
Share this answer
 
v3
SQL
Select Parent.Pid,Parent.Pname,Parent.Pemail,
       Left(Main.Child,Len(Main.Child)-1) As "ChildValues"
From(Select distinct Child2.SubjectID,
           (Select Child1.Cname AS [text()]
            From dbo.Child Child1
            Where Child1.Pid = Child2.Pid
            ORDER BY Child1.Pid
            For XML PATH ('')) [Child]
     From dbo.Child Child2) [Main]
 
Share this answer
 
SQL Server PIVOT[^] should help you out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900