[英]oracle query to group columns
I have a simple requirement but couldn't correctly get the required output. 我有一个简单的要求,但无法正确获取所需的输出。
I have 2 tables - parent, children 我有2张桌子-父母,孩子
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. 当您生孩子时,您还需要一个case表达式来抑制父对象。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.