What join should I use to get my desired output base on dummy table below
DETAIL TABLE
x------------------------------x
| empID | empName | date |
x------------------------------x
| 1 | emp1 | 10/01/2016 |
| 1 | emp1 | 10/03/2016 |
| 1 | emp1 | 10/04/2016 |
| 1 | emp1 | 10/05/2016 |
| 1 | emp1 | 10/06/2016 |
x------------------------------x
LIST DATES FROM 10/01/2016 to 10/15/2016 OF TABLE
x------------x
| date |
x------------x
| 10/01/2016 |
| 10/02/2016 |
| .......... |
| .......... |
| 10/15/2016 |
x------------x
Desired output for my query
x------------------------------x
| empID | empName | date |
x------------------------------x
| 1 | emp1 | 10/01/2016 |
| null | null | 10/02/2016 |
| 1 | emp1 | 10/03/2016 |
| 1 | emp1 | 10/04/2016 |
| 1 | emp1 | 10/05/2016 |
| 1 | emp1 | 10/06/2016 |
| null | null | 10/07/2016 |
| null | null | 10/08/2016 |
| null | null | 10/09/2016 |
| null | null | 10/10/2016 |
| null | null | 10/11/2016 |
| null | null | 10/12/2016 |
| null | null | 10/13/2016 |
| null | null | 10/14/2016 |
| null | null | 10/15/2016 |
x------------------------------x
Answer is OUTER JOIN
it can be either LEFT
or RIGHT
depending on where you are using the detail
table.
SELECT D.empid,
D.empname,
LD.[date]
FROM detail D
RIGHT OUTER JOIN list_dates LD
ON D.[date] = LD.[date]
Also you can use OUTER APPLY
SELECT D.empid,
D.empname,
LD.[date]
FROM list_dates LD
OUTER apply (SELECT *
FROM detail D
WHERE D.[date] = LD.[date]) D