我有3个表(sya A,B和C),它们之间有9个公共列(ID_number,company,Role,Seq_number,FirstName,MiddleName,LastName,Gender& DOB)。
表A有两种类型的记录
现在我只想比较表A中来自表B和B的那些记录。 C表B和表B中提供的记录C基于这9个常见列。表A和表A中的记录之间的一个共同列的数据可能存在差异。 (表B或C)。我只想选择那个特定的记录。
示例:
表A
ID_Number company Role Seq_Number FirstName MiddleName LastName Gender DOB system city state country
1234 12 OWN 1 Test1 mid1 last1 F 1979-01-26 ABC YYY ZZZ IND
表B或C
ID_Number company Role Seq_Number FirstName MiddleName LastName Gender DOB System address
1234 12 OWN 1 Test1 mid1 last1 F 1990-08-30 ABC IND
在上面的例子中,每个公共列彼此进行比较。只有列DOB不同。因此,我必须报告此记录。同样,如果任何此常见列不匹配的数据,我需要获取这些记录。我尝试在A,B,C之间使用过滤条件保持连接。但它没有按预期工作。
此外,表A中没有一列(比如类型)。但是可以在表B和B中找到。 C.我需要在获取不匹配的记录时从表B或表C中获取该列的值。当使用左连接来获取不匹配的记录时,我试图获得'类型'使用case / ISNULL / COALSCE从B或C中获取列值(因为表A中的记录将来自B或C)。但我只获得NULL值,尽管该列在B或C中具有值。
表B& C是表A的基础。因此表A具有来自B或C的记录。列(ID_Number,company,Role& seq_number)是所有3个表的主键,它们保持相同。只剩下的字段会改变。我尝试如下。它从表A中获取记录,这些记录在表B或C中也不可用。但是,只需要从B或C中可用的A中获取不匹配的记录。
SELECT ALC.ID_Number ,ALC.Role ,ALC.Seq_Number ,CASE WHEN BPC.Type IS NULL THEN CPC.Type ELSE BPC.Type END --,FAT_Cust.FATCA_PolicyOwner_Type AS Client_Type ,ALC.FirstName AS First_Name ,ALC.MiddleName AS Middle_Name ,ALC.LastName AS Last_Name ,ALC.Gender ,ALC.Date_Of_Birth AS DOB 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.FirstName = BPC.FirstName AND ALC.MiddleName = BPC.MiddleName AND ALC.LastName = BPC.LastName AND ALC.Gender = BPC.Gender AND ALC.DOB = BPC.DOB AND ALC.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.FirstName = CPC.FirstName AND ALC.MiddleName = CPC.MiddleName AND ALC.LastName = CPC.LastName AND ALC.Gender = CPC.Gender AND ALC.DOB = CPC.DOB AND ALC.Record_Active = 1 WHERE ALC.Record_Active = 1 AND (BPC.NAME IS NULL AND CPC.NAME IS NULL) AND (BPC.ROLE IS NULL AND CPC.ROLE IS NULL) AND (BPC.Seq_Number IS NULL AND CPC.Seq_Number IS NULL ) AND (BPC.FirstName IS NULL AND CPC.FirstName IS NULL) AND (BPC.MiddleName IS NULL AND CPC.MiddleName IS NULL) AND (BPC.LastName IS NULL AND CPC.LastName IS NULL) AND (BPC.Gender IS NULL AND CPC.Gender IS NULL) AND (BPC.DOB IS NULL AND CPC.DOB IS NULL) AND ALC. Record_Active =1 AND (ALC.UpdatedDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND GETDATE())
答案 0 :(得分:0)
我相信这应该对你有帮助,或者至少可以给你一个想法:
;WITH BC as (SELECT * FROM B UNION ALL SELECT * FROM C)
SELECT *
FROM BC LEFT JOIN A
ON BC.ID_number = A.ID_number and BC.company = A.company and
BC.Role = A.Role and BC.Seq_number = A.Seq_number
WHERE A.ID_number Is Null or
HASHBYTES('SHA2_256', IsNull(BC.FirstName,'') + IsNull(BC.MiddleName,'') + IsNull(BC.LastName,'') + IsNull(BC.Gender,'') + IsNull(CAST(BC.DOB as VARCHAR),'')) !=
HASHBYTES('SHA2_256', IsNull(A.FirstName,'') + IsNull(A.MiddleName,'') + IsNull(A.LastName,'') + IsNull(A.Gender,'') + IsNull(CAST(A.DOB as VARCHAR),''))