Reputation: 195
I have a simple requirement but couldn't correctly get the required output.
I have 2 tables - parent, children
in parent table I have the list of parents
P1
P2
P3
etc
In Child table I have records like
P1 | P1_C1
P1 | P1_C2
P2 | P2_C1
P2 | P2_C3
P3 | P3_C4
etc
I need to write a query which should return the following
Parent record in first row, followed by its children, Another parent record, followed by its children etc
Example:
------ | ------
P1 | null
null | P1_C1
null | P1_C2
P2 | null
null | P2_C1
null | P2_C3
P3 | nul
null | P3_C4
Upvotes: 0
Views: 38
Reputation: 94884
Select parent and child (where available) from both tables. Then sort by parent and children (with null children first). You also need a case expression to supress the parent when you show a child.
select case when c is null then p end as parent, c as child
from
(
select p, c from children
union all
select p, null from parents
)
order by p, c nulls first;
Upvotes: 1
Reputation: 518
Consider this solution, please. You should not use the first column, it is used only for proper sorting:
select
pa.id, null, ch.value
from
parent pa
join child ch on parent.id=child.id
union
select
pa2.id, pa2.id, null
from
parent pa2
order by 1, 3 nulls first;
Upvotes: 0