子查询 Select 语句中不包含的更新值
Update Value not Contained in Subquery Select Statement
我正在尝试使用 locationID 更新人员 table。但是,我只想在一个人只有 1 个地址时更新位置。
我试图组合一个子查询。但是,如果我在 select 语句中包含 Address 的 locationUD,那么它会为我提供每个人,甚至是有 2 个实际地址的人(因为他们没有多次住在一个地址。)
如何重写我的查询以仅在一个人出现在子查询中一次而不在 select 语句中包含 locationID 的情况下更新 locationID?
update p set locationID = n2.locationID
--select *
from
Personnel p
inner join (select p.personID,
count(*) AS 'Num of Households/Addresses'
--select *
from Person pe
inner join Address a on a.personID = pe.personID
group by pe.personID
having count(*) = 1) n2 on n2.personID = p.personID
你可以使用一个技巧。如果只有一个匹配项,则 min()
或 max()
会为您提供该行的值:
update p
set locationID = n2.locationID
from Personnel p inner join
(select a.personID, max(a.locationid) as locationid
from Address a
group by a.personID
having count(*) = 1
) n2
on n2.personID = p.personID;
注意子查询中不需要 person
table。您可以只使用 Address
table.
中的值
我正在尝试使用 locationID 更新人员 table。但是,我只想在一个人只有 1 个地址时更新位置。
我试图组合一个子查询。但是,如果我在 select 语句中包含 Address 的 locationUD,那么它会为我提供每个人,甚至是有 2 个实际地址的人(因为他们没有多次住在一个地址。)
如何重写我的查询以仅在一个人出现在子查询中一次而不在 select 语句中包含 locationID 的情况下更新 locationID?
update p set locationID = n2.locationID
--select *
from
Personnel p
inner join (select p.personID,
count(*) AS 'Num of Households/Addresses'
--select *
from Person pe
inner join Address a on a.personID = pe.personID
group by pe.personID
having count(*) = 1) n2 on n2.personID = p.personID
你可以使用一个技巧。如果只有一个匹配项,则 min()
或 max()
会为您提供该行的值:
update p
set locationID = n2.locationID
from Personnel p inner join
(select a.personID, max(a.locationid) as locationid
from Address a
group by a.personID
having count(*) = 1
) n2
on n2.personID = p.personID;
注意子查询中不需要 person
table。您可以只使用 Address
table.