【问题标题】:oracle query to group columnsoracle查询分组列
【发布时间】:2017-05-24 16:42:01
【问题描述】:

我有一个简单的要求,但无法正确获得所需的输出。

我有 2 张桌子 - 父母,孩子

在父表中我有父母列表

P1
P2
P3
etc

在子表中,我有类似

的记录
P1 | P1_C1
P1 | P1_C2
P2 | P2_C1
P2 | P2_C3
P3 | P3_C4
etc

我需要编写一个应该返回以下内容的查询

第一行的父记录,然后是它的子记录,另一个父记录,然后是它的子记录等

例子:

------ | ------
P1     |  null  
null   |  P1_C1   
null   |  P1_C2 
P2     |  null
null   |  P2_C1
null   |  P2_C3
P3     |  nul
null   |  P3_C4

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    从两个表中选择父级和子级(如果有)。然后按父母和孩子排序(首先是空孩子)。当你显示一个孩子时,你还需要一个 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;
    

    【讨论】:

      【解决方案2】:

      请考虑这个解决方案。您不应该使用第一列,它仅用于正确排序:

      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;
      

      【讨论】:

        猜你喜欢
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 2020-12-05
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多