我有一个查询三个临时表。
- 表一 当 PC = 6 而不是 7 时返回 PID
- 表二 当 PC = 1 而不是 7 时返回 PID
- 表三 返回 PID 而不是 7
前两个临时表有一个完美的内连接,只返回 PC = 6 和 PC = 1 的 PID,但不等于 7。
但是,我想要的是第三部分,在 PC 上右外连接,并返回所有包含 PC = 6 或 PC = 1 的 PID,而不是在内连接中。相反,右外连接返回相同的值。有人可以帮帮我吗?
--CREATE TEMP TABLE TO PULL PIDs w PLCs but no True Owner--
SELECT
Distinct P.PropertyID as PID
,PC.LocationID AS PLC
INTO #TempPLC
FROM
Property AS P
left join
PropertyContact As PC on PC.PropertyID = P.PropertyID
WHERE
P.PropertyID=PC.PropertyID
and
PC.ContactRoleID = 6
and not exists
(select 1
from
Enterprise.dbo.PropertyContact
where
PropertyID=P.PropertyID
and
ContactRoleID=7)
--CREATE TEMP TABLE TO PULL PIDs w Recorded but no True Owner--
USE ENTERPRISE--
SELECT
Distinct P.PropertyID as PID
,PC.LocationID AS Recorded
INTO #TempRecorded
FROM
Property AS P
left join
PropertyContact As PC on PC.PropertyID = P.PropertyID
WHERE
P.PropertyID=PC.PropertyID
and
PC.ContactRoleID = 3
(select 1
from
Enterprise.dbo.PropertyContact
where
PropertyID=P.PropertyID
and
ContactRoleID=7)
--CREATE TEMP TABLE TO PULL PIDs w PLCs but no True Owner--
SELECT
P.PropertyID as PID
,PC.LocationID AS RemainingLocs
INTO #TempRemaining
FROM
Property AS P
left join
PropertyContact As PC on PC.PropertyID = P.PropertyID
WHERE
P.PropertyID=PC.PropertyID
and not exists
(select 1
from
Enterprise.dbo.PropertyContact
where
PropertyID=P.PropertyID
and
ContactRoleID=7)
--RETURN RESULTS OF ALL PIDS w. BOTH RECORDED AND TRUE OWNERS--
SELECT
Distinct #TempRemaining.PID
,#TempRemaining.RemainingLocs
,#TempRecorded.Recorded
FROM
#TempPLC
inner join
#TempRecorded on #TempRecorded.PID = #TempPLC.PID
right join
#TempRemaining on #TempRecorded.Recorded = #TempRemaining.RemainingLocs
WHERE
#TempRecorded.Recorded = #TempPLC.PLC
--DROP TEMP TABLES--
drop table #TempPLC
drop table #TempRecorded
drop table #TempRemaining