SQL Server 2012 - 通过与另外两个表进行交叉检查来查询从表中检索匹配记录

时间:2016-05-30 10:01:48

标签: sql-server

我有三个表(比如A,B和C),它们具有相同的列名和数据类型。这些表可以使用四个唯一列连接,例如name,company,Seq_Number和role。现在我想从表A中选择特定角色的记录,并用表B和C中的记录进行交叉检查。如果它们在两个表中都不存在,那么我们需要从表A中停用/删除这些记录。问题表B中不存在的记录可能存在于表C中。因此,我需要删除特定角色的记录,只要它们在B& B中都不存在。 C表。我尝试了以下查询。但它没有返回预期的结果。请帮助我

SELECT DISTINCT FAT_Cust.name
              , FAT_Cust.Company
              , FAT_Cust.role
              , FAT_Cust.Seq_Number
              , Cust.name
              , Cus.Company
              , Cust.role
              , Cust.Seq_Numberfrom (
    SELECT DISTINCT ALC.NAME, ALC.Company, ALC.ROLE, ALC.Seq_Number
    FROM AL_Customer ALC
    INNER JOIN BL_Customer LPC ON ALC.NAME = LPC.NAME
        AND ALC.Company = LPC.Company
        AND ALC.ROLE = LPC.ROLE
        AND ALC.Seq_Number = LPC.Seq_Number
        AND ALC.Record_Active = 1

    UNION SELECT DISTINCT ALC.NAME, ALC.Company, ALC.ROLE, ALC.Seq_Number
    FROM AL_Customer ALC
    INNER JOIN CL_Customer CLC ON ALC.NAME = CLC.NAME
        AND ALC.Company = CLC.Company
        AND ALC.ROLE = CLC.ROLE AND ALC.Seq_Number = CLC.Seq_Number
        AND ALC.Record_Active = 1
) Cust
RIGHT OUTER JOIN AL_Customer FAT_Cust ON FAT_Cust.NAME = Cust.NAME
    AND FAT_Cust.Company = Cust.Company
    AND FAT_Cust.ROLE = Cust.ROLE
    AND FAT_Cust.Seq_Number = Cust.Seq_Number
    AND FAT_Cust.Record_Active = 1
WHERE Cust.NAME IS NULL
    AND Cust.Company IS NULL
    AND Cust.ROLE IS NULL
    AND Cust.Seq_Number IS NULL
    AND Cust.ROLE < > 'OWN'

1 个答案:

答案 0 :(得分:1)

请尝试下面给出的查询

SELECT ALC.* FROM AL_Customer ALC
    LEFT JOIN BL_Customer BPC ON ALC.NAME = BPC.NAME
        AND ALC.Company = BPC.Company
        AND ALC.ROLE = BPC.ROLE
        AND ALC.Seq_Number = BPC.Seq_Number
        AND ALC.Record_Active = 1 
        AND BLC.Record_Active = 1

    LEFT JOIN CL_Customer CPC ON ALC.NAME = CPC.NAME
        AND ALC.Company = CPC.Company
        AND ALC.ROLE = CPC.ROLE
        AND ALC.Seq_Number = CPC.Seq_Number
        AND ALC.Record_Active = 1 
        AND CLC.Record_Active = 1
WHERE ALC.Record_Active = 1 
AND (BPC.NAME IS NULL) 
AND (CPC.NAME IS NULL)

你可以添加更多条件是在哪里类来缩小匹配条件。上面的查询假设表中的所有记录都存在名称。我希望这能解决你的问题。