从同一 table 中的两个独立员工记录中获取 new/old 值

Obtaining new/old values from two seperate employee records in same table

我想为数据库中的每个员工打印一行数据table,每个员工有两行数据,一行是他们当前的工作职位,另一行是他们的后备职位。

每个员工的员工 table 看起来像这样:

|EMPLNO| FNAME | LNAME    |JOBNO| TITLE | TITLE_DT  |STATUS|
------------------------------------------------------------
|  577 | Jon   | Albeary  | 1   | 54737 | 8/15/2016 | C    |
------------------------------------------------------------
|  577 |  Jon  | Albeary  | 2   | 8297A | 4/1/2019  | T    |
------------------------------------------------------------

结果应如下所示:

|EMPLNO| FNAME | LNAME    |JOBNO| TITLE | TITLE_DT  |STATUS| BKUP_TITLE | BKUP_TITLE_DT  |BKUP_STATUS|
---------------------------------------------------------------------------------------------------------
|  577 | Jon   | Albeary  | 1   | 54737 | 8/15/2016 | C    | 8297A      | 4/1/2019       | T         |
---------------------------------------------------------------------------------------------------------

SQL 要求是查找所有带 (JOBNO = '1') AND(EMPL_CLASS <> 'A') 的记录,但有一条带 (JOBNO = '2') AND (TITLE = '54737') 的记录。我得到了结果,但不知道如何从第二条记录中获取信息,并列在一行中。

我的 SQL 看起来像这样:

SELECT EMPLNO, FNAME, LNAME, STATUS, TITLE, TITLE_DT 
FROM  EMPLOYEE
WHERE (EMPLNO IN
           (SELECT EMPLNO
            FROM  EMPLOYEE AS EMPLOYEE_1
            WHERE (JOBNO = '2') AND (TITLE = '54737'))) 
AND (JOBNO = '1') AND (STATUS <> 'A');

但是,该查询只给了我 JOBNO = 1 的记录。谁能帮我写一个查询,将 JOBNO = 1 和 JOBNO = 2 的记录打印在一行上?

谢谢。

您可以通过首先选择 jobno = 2 的所有记录,然后将其连接到员工编号匹配的 jobno = 1 的记录来连接 table 本身。

    select a.emplno, a.fname, a.lname, a.status, b.title as bkup_title, b.title_dt as bkup_title_dt, b.status as bkup_Status
    from (select * from employee where jobno = '2' and title = '54737') b
    join employee a
    on a.emplno = b.emplno
    wherre a.jobno = '1' and a.status <> 'A';

您可以通过自连接来完成:

select e.*,
  ee.title as BKUP_TITLE, ee.title_dt as BKUP_TITLE_DT, ee.status as BKUP_STATUS
from employee e inner join employee ee
on ee.emplno = e.emplno
where e.status<> 'A' and e.title = '54737' and e.jobno = 1 and ee.jobno = 2

参见demo
结果:

| EMPLNO | FNAME | LNAME   | JOBNO | TITLE | TITLE_DT   | STATUS | BKUP_TITLE | BKUP_TITLE_DT | BKUP_STATUS |
| ------ | ----- | ------- | ----- | ----- | ---------- | ------ | ---------- | --------------| ----------- |
| 577    | Jon   | Albeary | 1     | 54737 | 2016-08-05 | C      | 8297A      | 2019-04-01    | T           |