如果我有两个表格 TABLE1 AND TABLE2
TABLE1
DEPTNO EMPID
10 1
10 2
10 3
TABLE2
EMPID PRJNAME
1 ABC
1 DEF
3 XYZ
THE QUERY
SELECT T1.*,T2.PRJNAME
FROM
TABLE1 T1,
TABLE2 T2
WHERE
T1.EMPID = T2.EMPID;
将作为输出
DEPTNO EMPID PRJNAME
10 1 ABC
10 1 DEF
10 3 XYZ
如何修改QUERY以输出结果
DEPTNO EMPID PRJNAME
10 1 ABC
DEF
3 XYZ
答案 0 :(得分: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;
答案 1 :(得分: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
;