0

我想比较一下联系人表中的地址字段是否与交货表中的地址字段不同。

SELECT contactID, addressline1
FROM contact
where contactID = '0018319'

下面是包含旧细节的交货表。

SELECT contactID, addressline1
FROM delivery
where contactID = '0018319'
4

2 回答 2

2
SELECT contactID, d.addressline1, c.addressline1
FROM delivery d
INNER JOIN contact c on d.contactID = c.contactID
where d.addressline1 != c.addressline1
于 2013-05-10T09:11:35.270 回答
0

如果要返回标志,则可以caseselect语句中使用:

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';

这将比较两个表中的每个地址。

如果你想知道是否相同,那么查询就更复杂了。这个想法是full outer join在两个表之间(对于给定的contractid)做一个addressline1。如果所有地址线都匹配,则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)
于 2013-05-10T13:33:50.910 回答