[英]comparing fields in 2 different tables using SQL
我想比較聯系表中的地址字段是否與交付表的地址字段不同。
SELECT contactID, addressline1
FROM contact
where contactID = '0018319'
以下是包含舊詳細信息的交付表。
SELECT contactID, addressline1
FROM delivery
where contactID = '0018319'
SELECT contactID, d.addressline1, c.addressline1
FROM delivery d
INNER JOIN contact c on d.contactID = c.contactID
where d.addressline1 != c.addressline1
如果要返回一個標志,那么你將在select
語句中使用case
:
select contactId,
(case when d.addressline1 = c.addressline1 or d.addressline1 is null and c.addressline1 is null
then 'SAME'
else 'DIFFERENT'
end) as SameOrDifferent
from contact c join
delivery d
on c.contactId = d.contactId
where contactId = '0018319';
這將比較兩個表中的每個地址。
如果您想知道是否所有內容都相同,那么查詢會更復雜。 我們的想法是在addressline1
上的兩個表(對於給定的contractid
)之間進行full outer join
。 如果所有地址行都匹配,則full outer join
將永遠不會產生NULL
值。 如果缺少任何一個(在任何一側),那么將有NULL值。
select coalesce(c.contactId, d.contactId) as contactId,
(case when sum(case when c.addressline1 is null or d.addressline1 is null
then 1
else 0
end) = 0
then 'SAME'
else 'DIFFERENT'
end) as SameOrDifferent
from (select c.* from contact c where c.contactId = '0018319') c full outer join
(select d.* from delivery d where d.contactId = '0018319') d
on c.addressline1 = d.addressline1 and
c.contactId = d.contactId -- not actually necessary but useful for multiple contacts
group by coalesce(c.contactId, d.contactId)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.