使用SQL比较2个不同表中的字段

时间:2013-05-10 09:07:05

标签: sql sql-server

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

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

下面是包含旧详细信息的交付表。

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

2 个答案:

答案 0 :(得分:2)

SELECT contactID, d.addressline1, c.addressline1
FROM delivery d
INNER JOIN contact c on d.contactID = c.contactID
where d.addressline1 != c.addressline1

答案 1 :(得分:0)

如果您想返回一个标志,那么您可以在case声明中使用select

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)