0

我正在尝试将同一张表与其自身进行比较,以将一个员工的位置与另一个进行比较。我希望能够选择一名员工是否仅在另一名员工的某个位置。

表看起来像这样

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,但它似乎不起作用。

4

4 回答 4

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
于 2012-10-05T13:43:19.553 回答
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
于 2012-10-05T13:52:41.253 回答
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) 
于 2012-10-06T16:16:10.037 回答
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))
于 2012-10-05T13:51:11.893 回答