简体   繁体   中英

oracle query to group columns

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

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM