我已经在 StackOverflow 和 Google 上搜索过这个问题的答案。
我正在尝试创建一个 Microsot SQL Server 2008 视图。不是存储过程。不是函数。只是一个查询(即一个视图)。
我有三张桌子。第一个表定义了一个公共键,比如“CompanyID”。其他两个表有一个有时很常见的字段,比如“EmployeeName”。
我想要一个表结果,当我的 WHERE 子句说“WHERE CompanyID = 12”时,它看起来像这样:
CompanyID | TableA | TableB
12 | John Doe | John Doe
12 | Betty Sue | NULL
12 | NULL | Billy Bob
我尝试了一个看起来像这样的 FULL OUTER JOIN:
SELECT Company.CompanyID,
TableA.EmployeeName,
TableB.EmployeeName
FROM Company
FULL OUTER JOIN TableA ON Company.CompanyID = TableA.CompanyID
FULL OUTER JOIN TableB ON
Company.CompanyID = TableB.CompanyID AND
(TableA.EmployeeName IS NULL OR TableB.EmployeeName IS NULL OR TableB.EmployeeName = TableA.EmployeeName)
我只从一个匹配的表中获取 NULL,我没有得到另一个表的扩展。在上面的示例中,我基本上只得到第一行和第三行,而不是第二行。
有人可以帮我创建这个查询并告诉我这是如何正确完成的吗?
顺便说一句,我已经有一个看起来非常干净并填充内存表的存储过程,但这不是我想要的。
谢谢。
- 编辑:
这是当前不起作用的完整示例(缺少“某人 2”和“某人 3”。
DECLARE @Company TABLE
(
CompanyID int
)
INSERT INTO @Company (CompanyID) VALUES (10)
INSERT INTO @Company (CompanyID) VALUES (12)
DECLARE @TableA TABLE
(
EmployeeId int,
CompanyId int,
EmployeeName varchar(30)
)
DECLARE @TableB TABLE
(
EmployeeId int,
CompanyId int,
EmployeeName varchar(30)
)
INSERT INTO @TableA ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 1, 10, 'someone' )
--INSERT INTO @TableA ( EmployeeId, CompanyId, EmployeeName )
--VALUES ( 2, 12, 'someone 2' )
INSERT INTO @TableA ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 3, 12, 'someone 3' )
INSERT INTO @TableA ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 3, 12, 'someone 4' )
INSERT INTO @TableB ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 1, 10, 'someone' )
INSERT INTO @TableB ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 2, 12, 'someone 2' )
--INSERT INTO @TableB ( EmployeeId, CompanyId, EmployeeName )
--VALUES ( 3, 12, 'someone 3' )
INSERT INTO @TableB ( EmployeeId, CompanyId, EmployeeName )
VALUES ( 3, 12, 'someone 4' )
SELECT Company.CompanyID,
TableA.EmployeeName,
TableB.EmployeeName
FROM @Company Company
FULL OUTER JOIN @TableA TableA ON Company.CompanyID = TableA.CompanyID
FULL OUTER JOIN @TableB TableB ON Company.CompanyID = TableB.CompanyID
WHERE
(
TableA.EmployeeName IS NULL OR TableB.EmployeeName IS NULL OR
TableB.EmployeeName = TableA.EmployeeName
)
AND Company.CompanyID = 12
结果:
CompanyID EmployeeName EmployeeName
12 someone 4 someone 4
我想要的是:
CompanyID EmployeeName EmployeeName
12 NULL someone 2
12 someone 3 NULL
12 someone 4 someone 4