SQL找到两个表之间的区别

时间:2014-03-19 08:51:46

标签: sql sql-server join compare

我需要比较两个表(表A作为生产数据,B作为旧数据)之间的电子邮件记录(通过电子邮件地址)来查找差异并在列中显示结果,例如" New", "删除"等等。

如果表A中存在,而不是表B中,则应标记"新"

否则,如果表B中存在,而不是表A中,则应标记"删除"

如果出现在两个表中,则应标记"维护"

我想要那样的结果

DisplayName     LastName    Diremail    Result
==============================================
XXX             XXX         a@a.com     New
ABC             ABC         1@a.com     Delete
DDD             DDD         2@a.com     Maintain

我的代码如下:

SELECT  b.DisplayName,
        b.LastName,
        b.diremail,        
        Result = CASE WHEN a.DirEmail IS NULL THEN 'New'   
        when b.DirEmail IS null then 'delete'     
                    else 'Maintain'
                END
FROM    vHRIS_StaffDB b    
        LEFT JOIN HRIS_DL_Lists a
            ON a.DirEmail = b.DirEmail
WHERE (
a.DirEmail IS NULL
OR      a.DisplayName != b.DisplayName
)

但数据不正确,因为代码不返回记录,应该"删除" (见表b,而不是表a)

请指教。谢谢。

1 个答案:

答案 0 :(得分:0)

听起来你需要完全加入而不是左连接。试试这个:

SELECT  coalesce(b.DisplayName, a.DisplayName) DisplayName,
        coalesce(b.LastName, a.LastName) LastName,
        coalesce(b.diremail, a.diremail) diremail,
        Result = CASE WHEN a.DirEmail IS NULL THEN 'New'   
        when b.DirEmail IS null then 'delete'     
                    else 'Maintain'
                END
FROM    vHRIS_StaffDB b    
        FULL JOIN HRIS_DL_Lists a
            ON a.DirEmail = b.DirEmail
WHERE (
a.DirEmail IS NULL
OR      a.DisplayName != b.DisplayName
)