I can't quite seem to figure out how to add data only where it exists.
I have a statement that I would like to add fields to. But rather than only pulling Employees if the criteria is met (ie the WHERE statement) I would like to associate the data if and only if it exists. My base statement pulls 30 records, but when I add more details to my WHERE statement (to include other fields), it drops the record count to 20. How do I retain my 30 records, while also including details from separate tables (if they exist)?
My base statement - it pulls 30 records
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;
Output 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
Detailed Statement to include extra fields - it only pulls 20 records
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;
Output Example
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
Here is what I tried to do, but it only duplicated the 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;
My last attempt pulls the data, but doesn't seem adhere to the CASE WHEN statement and duplicates a lot of the records. Please let me know if that doesn't make sense. Any help or tips you can provide would be much appreciated.
Thanks in advance!
left joininstead ofjoin. This way when no related rows exist, you'll still get the main row (and null values in the related columns).