SQL查询将具有一对多关系的两个表与第一表行和第二行的后续行连接起来

时间:2018-06-21 16:24:15

标签: sql oracle plsql

对于以下要求,我需要有关查询/ PL / SQL过程的帮助。

表1:

T1ID      T1Name       T1Col2
 1        Name1          X
 2        Name2          Y

表2:

T2T1ID    T2SubName    T2Column2
1         Test1Sub1       P
1         Test1Sub2       P
1         Test1Sub3       P
2         Test2Sub1       Q
2         Test2Sub2       Q

我想建立一个查询来获取我

T1ID              T1Name              T1Col2        T2SubName      T2Column2
  1                Test1               X
                                                     Test1Sub1       P
                                                     Test1Sub2       P
                                                     Test1Sub3       P
  2                Test2               Y
                                                     Test2Sub1       Q
                                                     Test2Sub1       Q

2 个答案:

答案 0 :(得分:1)

任何报告工具都可以轻松实现这种“中断”布局。在SQL * Plus中,BREAK(谁会猜到?)可以完成这项工作。看看是否有帮助。

SQL> break on t1id on t1name on t1col2
SQL>
SQL> with
  2  t1 (t1id, t1name, t1col2) as
  3    (select 1, 'name1', 'x' from dual union
  4     select 2, 'name2', 'y' from dual
  5    ),
  6  t2 (t2t1id, t2subname, t2column2) as
  7    (select 1, 'test1sub1', 'p' from dual union
  8     select 1, 'test1sub2', 'p' from dual union
  9     select 1, 'test1sub3', 'p' from dual union
 10     select 2, 'test2sub1', 'q' from dual union
 11     select 2, 'test2sub2', 'q' from dual
 12    )
 13  select a.t1id, a.t1name, a.t1col2, b.t2subname, b.t2column2
 14  from t1 a join t2 b on b.t2t1id = a.t1id
 15  order by a.t1id;

      T1ID T1NAM T T2SUBNAME T
---------- ----- - --------- -
         1 name1 x test1sub1 p
                   test1sub2 p
                   test1sub3 p
         2 name2 y test2sub1 q
                   test2sub2 q

SQL>

答案 1 :(得分:0)

在FULL OUTER JOIN中使用正确的ORDER BY语句:

select t1.t1id, nvl2(t1.t1name,'Test'||t1.t1id,'') t1name, t1.col2, 
       t2.t2subname, t2.t2column2 
  from table1 t1
  full outer join table2 t2
  on ( t1.col2 = t2.t2column2 )
order by nvl(t1id,2)||nvl(t2t1id,2), nvl(t2.t2subname,'0');

T1ID    T1NAME  COL2    T2SUBNAME   T2COLUMN2
----    ------  ----    ---------   ---------
 1      Test1   X       
                        Test1Sub1   P
                        Test1Sub2   P
                        Test1Sub3   P
 2      Test2   Y       
                        Test2Sub1   Q
                        Test2Sub2   Q

db <> fiddle demo