2016-06-01 4 views
0

人事テーブルをlocationIDで更新しようとしています。しかし、人が1つのアドレスしか持たない場合は、その場所を更新したいだけです。サブクエリに含まれない更新値の選択ステートメント

サブクエリをまとめようとしました。しかし、selectステートメントにAddressからlocationUDを含めると、2つの実際の住所を持つ人でさえも(住所に2回以上住んでいないので)誰もが私に与えます。

locationIDを更新するクエリは、select文に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 

答えて

2

トリックを使用できます。唯一の一致がある場合は、min()またはmax()はあなたにその行から値を取得する:personテーブルがサブクエリで必要とされないことを

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; 

注意してください。 Addressテーブルの値をそのまま使用できます。

関連する問題