Soldato
- Joined
- 14 Feb 2004
- Posts
- 14,315
- Location
- Peoples Republic of Histonia, Cambridge
I have some relational data I need to export to a customer as a flat table excel document.
For arguments sake lets say the data is a simple parent child relationship.
Parent
-----------
ParentID
ParentName
Child
-----------
ChildID
ParentID
ChildName
Let’s also say for arguments sake a parent can have no more than 3 children.
How would I get the information into the format below using an SQL statement?
Export
-----------
ParentID
ParentName
FirstChildName
SecondChildName
ThirdChildName
If a parent has less than 3 children the child columns are nullable.
EDIT: I forgot to say I'm using SQL Server 2005.
I think I've found a way using three sub queries, but it's a bit messy. It depends on numbering each of the children from 1 to 3 for each parent.
Each subquery would look something like this -
I'm not sure if it works because I've only go access to an Oracle database at the moment. If any one can confirm it might work or suggest a better solution I'd be grateful.
For arguments sake lets say the data is a simple parent child relationship.
Parent
-----------
ParentID
ParentName
Child
-----------
ChildID
ParentID
ChildName
Let’s also say for arguments sake a parent can have no more than 3 children.
How would I get the information into the format below using an SQL statement?
Export
-----------
ParentID
ParentName
FirstChildName
SecondChildName
ThirdChildName
If a parent has less than 3 children the child columns are nullable.
EDIT: I forgot to say I'm using SQL Server 2005.
I think I've found a way using three sub queries, but it's a bit messy. It depends on numbering each of the children from 1 to 3 for each parent.
Each subquery would look something like this -
Code:
SELECT RANK() OVER (ORDER BY c.ChildName) as Rank, c.ChildName
FROM Child c
WHERE c.ParentID = p.ParentID
AND Rank = [1-3]
ORDER BY Rank
I'm not sure if it works because I've only go access to an Oracle database at the moment. If any one can confirm it might work or suggest a better solution I'd be grateful.
Last edited: