ORACLE SQL:使用嵌套条件

时间:2018-05-31 19:06:56

标签: sql oracle

我似乎无法弄清楚如何仅在存在的地方添加数据。

我有一个声明,我想添加字段。但是,如果满足条件(即WHERE语句),我不想仅提取员工,而是仅在数据存在的情况下关联数据。我的基本语句提取了30条记录,但是当我向WHERE语句添加更多详细信息(包括其他字段)时,它会将记录数减少到20条。如何保留30条记录,同时还包括单独表格的详细信息(如果它们存在)?

我的基本陈述 - 它提取了30条记录

SELECT DISTINCT EMPLOYEE_NUM "Employee #", 
START_DATE "Start Date",
NAME "Employee Name"
FROM EMPLOYEES E
JOIN EMPLOYEE_DETAILS D ON D.EMPLOYEE_ID = E.EMPLOYEE_ID
WHERE D.START_DATE >= DATE '2016-12-14'
ORDER BY 1;

输出Ex。

    Employee # | Start Date | Employee Name
    1234         12/15/2017   Jim Doe
    1456         01/16/2017   John Dillin
    5435         04/23/2017   Jane Mitchel
    9876         09/12/2017   Joan Smith
    7655         10/14/2017   Barry Gibb 
   ...25 more records

包含额外字段的详细声明 - 它只提取20条记录

SELECT DISTINCT EMPLOYEE_NUM "Employee #", 
START_DATE "Start Date",
NAME "Employee Name",
OS.ONBOARDING_LOCATION "On-boarding Location",
OS.COMPLETION_DATE "Completion Date"
FROM EMPLOYEES E
JOIN EMPLOYEE_DETAILS D ON D.EMPLOYEE_ID = E.EMPLOYEE_ID
JOIN ONBOARDING_STATUS OS ON OS.EMPLOYEE_ID = E.EMPLOYEE_ID
WHERE D.START_DATE >= DATE '2016-12-14'
AND OS.DESCRIPTION LIKE 'START'
AND OS.CANCELLED IS NULL
ORDER BY 1;

输出示例

    Employee # | Start Date | Employee Name | On-boarding Location | Completion Date
    1234         12/15/2017   Jim Doe           Sacramento, CA         12/13/2017
    1456         01/16/2017   John Dillin       Atlanta, GA            01/19/2017
    7655         10/14/2017   Barry Gibb        Los Angeles, CA        10/17/2017
   ...17 more records

这是我尝试做的,但它只复制了记录:

SELECT DISTINCT EMPLOYEE_NUM "Employee #", 
START_DATE "Start Date",
NAME "Employee Name",
(CASE 
   WHEN OS.DESCRIPTION LIKE 'START' AND OS.CANCELLED IS NULL
   THEN OS.ONBOARDING_LOCATION
   ELSE NULL
END)"On-boarding Location",
(CASE 
   WHEN OS.DESCRIPTION LIKE 'START' AND OS.CANCELLED IS NULL
   THEN OS.COMPLETION_DATE
   ELSE NULL
END)"Completion Date"
FROM EMPLOYEES E
JOIN EMPLOYEE_DETAILS D ON D.EMPLOYEE_ID = E.EMPLOYEE_ID
JOIN ONBOARDING_STATUS OS ON OS.EMPLOYEE_ID = E.EMPLOYEE_ID
WHERE D.START_DATE >= DATE '2016-12-14'
ORDER BY 1;

我的最后一次尝试提取数据,但似乎不遵守CASE WHEN语句并复制了大量记录。如果这没有意义,请告诉我。您可以提供的任何帮助或提示将不胜感激。

提前致谢!

1 个答案:

答案 0 :(得分:2)

使用 OUTER 加入,如:

SELECT
    DISTINCT EMPLOYEE_NUM "Employee #", 
    START_DATE "Start Date",
    NAME "Employee Name",
    OS.ONBOARDING_LOCATION "On-boarding Location",
    OS.COMPLETION_DATE "Completion Date"
  FROM EMPLOYEES E
  left JOIN EMPLOYEE_DETAILS D ON D.EMPLOYEE_ID = E.EMPLOYEE_ID
   and D.START_DATE >= DATE '2016-12-14'
  left JOIN ONBOARDING_STATUS OS ON OS.EMPLOYEE_ID = E.EMPLOYEE_ID
   AND OS.DESCRIPTION LIKE 'START'
   AND OS.CANCELLED IS NULL
  ORDER BY 1;

请注意我已将过滤条件(WHERE部分)移到join子句中以强制执行外连接。如果您将过滤器保留在WHERE子句中,则有效地将连接转换回内部连接,并且您不希望这样做。