SQL 服务器 JOIN/APPLY 查询
SQL Server JOIN/APPLY Query
我应该使用什么连接来根据下面的虚拟 table 获得我想要的输出
详情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
列出日期从 10/01/2016 到 10/15/2016 OF TABLE
x------------x
| date |
x------------x
| 10/01/2016 |
| 10/02/2016 |
| .......... |
| .......... |
| 10/15/2016 |
x------------x
我的查询所需的输出
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
看来您只需要 outer join
:
select e.empid, e.empname, d.date
from dates d
left join detail e on d.date = e.date
答案是 OUTER JOIN
它可以是 LEFT
或 RIGHT
取决于你在哪里使用 detail
table。
SELECT D.empid,
D.empname,
LD.[date]
FROM detail D
RIGHT OUTER JOIN list_dates LD
ON D.[date] = LD.[date]
您也可以使用 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
我应该使用什么连接来根据下面的虚拟 table 获得我想要的输出
详情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
列出日期从 10/01/2016 到 10/15/2016 OF TABLE
x------------x
| date |
x------------x
| 10/01/2016 |
| 10/02/2016 |
| .......... |
| .......... |
| 10/15/2016 |
x------------x
我的查询所需的输出
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
看来您只需要 outer join
:
select e.empid, e.empname, d.date
from dates d
left join detail e on d.date = e.date
答案是 OUTER JOIN
它可以是 LEFT
或 RIGHT
取决于你在哪里使用 detail
table。
SELECT D.empid,
D.empname,
LD.[date]
FROM detail D
RIGHT OUTER JOIN list_dates LD
ON D.[date] = LD.[date]
您也可以使用 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