子查询中不包含的更新值选择语句

时间:2016-06-01 01:29:28

标签: sql sql-server subquery

我正在尝试使用locationID更新人员表。但是,我只想在一个人只有一个地址时更新位置。

我试图组合一个子查询。但是,如果我在select语句中包含地址中的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

1 个答案:

答案 0 :(得分:2)

你可以使用技巧。如果只有一个匹配项,则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表。您只需使用Address表中的值。