Click here to Skip to main content
13,254,187 members (64,498 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I want to join two tables data and want these data in a single row
Table Parent
Pid Pname Pemail
1 Sumit
2 Neeraj
3 Manish

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
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 bhikhu
2 Neeraj dhiraj
2 Neeraj monu

But i want it in this format
Pid Pname Pemail Cname1 Cname2 Cname3
2 Neeraj bhikhu dhiraj monu

Please Help.
Posted 9-Jan-13 4:50am
Updated 9-Jan-13 6:01am
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

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

and for Help check this link [^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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]
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

SQL Server PIVOT[^] should help you out.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.171114.1 | Last Updated 13 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100