我正在尝试将同一个表与自己进行比较,以便将一个员工位置与另一个员工位置进行比较。我希望能够选择一名员工是否只在另一名员工的某个位置。
表格看起来像这样
StaffNo LocoNo
1 1
1 2
1 3
3 2
3 3
3 4
4 1
4 2
5 2
5 3
6 1
6 2
比较工作人员1和4
结果将是
StaffNo LocoNo
1 3
我尝试了内部联接和EXCEPT,但似乎它不起作用。
答案 0 :(得分:1)
内部联接仅在联接的两侧匹配时返回结果。当您在寻找差异时,您需要一个外部联接。像这样。
select
COALESCE(t1.staffid, t2.staffid) as staff,
COALESCE(t1.locationid, t2.locationid) as location
from
(select * from table where staffid=1) t1
full outer join
(select * from table where staffid=4) t2
on t1.locationid = t2.locationid
where t1.locationid is null
or t2.locationid is null
答案 1 :(得分:1)
另一种使用MINUS / UNION ALL的解决方案:
with
v_1 as (select locono from from table where staffid=1),
v_2 as (select locono from from table where staffid=2)
select * from (
(select 1 staffid, locono from v_1
minus
select 1 staffid, locono from v_2
)
union all
(
select 2 staffid, locono from v_2
minus
select 2 staffid, locono from v_1
)) order by staffid, locono
答案 2 :(得分:1)
SELECT StaffNo
, LocoNo
FROM Tbl A
WHERE NOT EXISTS
(SELECT 1
FROM Tbl B
WHERE A.StaffNo <> B.StaffNo
AND A.LocoNo = B.LocoNo)
答案 3 :(得分:0)
select staffno,locono from tbl where staffno in (1,4) and locono in
((select locono from tbl where staffno = 1
except
select locono from tbl where staffno = 4)
union
(select locono from tbl where staffno = 4
except
select locono from tbl where staffno = 1))