2016-10-25 67 views
0

如果我有兩個表 TABLE1TABLE2ORACLE - 分類部分輸出

TABLE1 
DEPTNO EMPID 
10  1 
10  2 
10  3 

TABLE2 
EMPID PRJNAME 
1  ABC 
1  DEF 
3  XYZ 

查詢

SELECT T1.*,T2.PRJNAME FROM TABLE1 T1, TABLE2 T2 WHERE T1.EMPID = T2.EMPID;

會給予AS

DEPTNO EMPID PRJNAME 
10  1  ABC 
10  1  DEF 
10  3  XYZ 
輸出

如何能查詢進行修改,以將結果輸出爲

DEPTNO EMPID PRJNAME 
10  1  ABC 
       DEF 
     3  XYZ 
+0

你在使用生成您的報告?這是應該由您的報告工具處理的事情,而不是在SQL中。可以用SQL來完成,但最好是讓報告工具來處理它,因爲這就是他們設計能夠做到的(一般情況)。 – Boneist

回答

1

首先,from子句中從未使用逗號。 始終使用使用正確的,明確的join語法。

二,SQL結果集是無序集。你的結果集似乎假設了一個排序,但它沒有order by

我假設你打算:

select t1.*, t2.prjname 
from table1 t1 join 
    table2 t2 
    on t1.empid = T2.empid 
order by t1.deptno, t1.empid, t2.prjname; 

然後,你可以做你想做什麼用窗函數:

select (case when lag(t1.deptno) over (partition by t1.deptno order by t1.empid, t2.prjname) is null 
      then t1.deptno 
     end) as deptno, 
     (case when lag(t1.empid) over (partition by t1.deptno, t1.empid order by t2.prjname) is null 
      then t1.empid 
     end) as deptno, 
     t2.prjname 
from table1 t1 join 
    table2 t2 
    on t1.empid = T2.empid 
order by t1.deptno, t1.empid, t2.prjname; 
+0

代碼需要修復。 (1)用** t2.prjname **(2)替換第二個CASE的't2.projname',替換'then t1.deptno end)as deptno' with ** then t1.empid end)as empid * * –

+0

@DuduMarkovitz。 。 。謝謝。 –

0
select  case row_number() over (partition by t1.deptno   order by t1.empid,t2.prjname) when 1 then t1.deptno end  as deptno 
      ,case row_number() over (partition by t1.deptno,t1.empid order by t2.prjname)   when 1 then t1.empid end  as empid 
      ,t2.prjname 

from     table1 t1 

      join  table2 t2 

      on   t1.empid = t2.empid 

order by t1.deptno 
      ,t1.empid 
      ,t2.prjname 
;