Oracle 中的自连接 SQL - 根据 1 个相同的列和 1 个不同的列选择行

Self-join in Oracle SQL - selecting rows based on 1 same column and 1 different column

这可能不是我需要的自连接,但我遇到了这个问题,希望有人能帮助我。

示例数据:

Row   Code   ReservationID   ClientID EmployeeID
1     T            123          7777     John 
2     T            456          2020     John
3     P            456          2020     John
4     P            999          3100     Steve
5     P            876          3100     Steve
6     T            333          2424     John
7     P            333          2424     Lynda

期望的输出:

Row   Code   ReservationID   ClientID EmployeeID
2     T            456          2020     John
3     P            456          2020     John
6     T            333          2424     John
7     P            333          2424     Lynda

我正在寻找仅 return 第 2、3、6 和 7 行的查询。

selection 条件是当有一行代码 = T 和另一行代码 = P 但具有相同的 Reservation ID 和 CLientID 时。 EmployeeID 可能相同或不同(我想 return 结果中的 EmployeeID 但不在 select 条件中使用它)。

阅读论坛我想我需要一个自助加入(我不知道该怎么做)。您能提供的任何帮助将不胜感激!谢谢!

一种方法使用 exists:

select t.*
from t
where (t.code = 'T' and exists (select 1 from t t2 where t2.reservationId = t.reservationId and t2.clientId = t.clientId and t2.code = 'P'
                               )
      ) or
      (t.code = 'P' and exists (select 1 from t t2 where t2.reservationId = t.reservationId and t2.clientId = t.clientId and t2.code = 'T'
                               )
      );

为了性能,您需要 (reservationId, clientId, code) 上的索引。

我认为更方便的方法是使用 row_number window 函数。您将为同一 ReservationIDClientID 中的每一行按 Code 的降序给出行号,然后根据此编号进行过滤:

SELECT Row, Code, ReservationID, ClientID, EmployeeID
FROM   (SELECT Row, Code, ReservationID, ClientID, EmployeeID,
               ROW_NUMBER() OVER (PARTITION BY ReservationID, ClientID
                                  ORDER BY Code DESC) AS rn
        FROM   mytable) t
WHERE  rn = 1

我认为最简单的解决方案是:

select distinct t1.*
  from my_table t1
  join my_table t2 on t1.reservationid = t2.reservationid
  where t1.code = 'T' and t2.code = 'P'
     or t1.code = 'P' and t2.code = 'T';