SQL Server:比较两个或多个表中的值

时间:2016-08-02 19:43:45

标签: sql sql-server

我必须编写一个查询,比较两个系统(系统A和系统B)之间的数据。在最终输出表中,我应该SystemA_FieldSystemB_Field后跟SystemA_Value,{ {1}}(见下文)。

这将比较两个系统的值以及两个系统的列名称。

换句话说,列必须与列值一起在行中。

enter image description here

2 个答案:

答案 0 :(得分:0)

内部查询的结果出了什么问题?

     SELECT     
         ContractType, 
         LeaseType,
         ContractNo,  
         ContractNumber
     FROM         
         TableOne INNER JOIN 
         TableA ON 
         ContractNo = ContractNumber
     WHERE     
         ContractNo = 101 

答案 1 :(得分:0)

您无需输出ContractNo& ContractNumber,因为它们必须始终匹配:

SELECT t1.ContractNo, t2.ContractNumber,
CASE 
    WHEN t1.ContractType != t2.LeaseType THEN 'ContractType' 
    WHEN t1.[Address] != t2.AddressMain THEN 'Address' 
    ELSE 'N/A' END as SystemA_Field,
CASE 
    WHEN t1.ContractType != t2.LeaseType THEN 'LeaseType' 
    WHEN t1.[Address] != t2.AddressMain THEN 'AddressMain' 
    ELSE 'N/A' END as SystemB_Field,
CASE 
    WHEN t1.ContractType != t2.LeaseType THEN CAST(ContractType as VARCHAR)
    WHEN t1.[Address] != t2.AddressMain THEN CAST(Address as VARCHAR)
    ELSE 'N/A' END as SystemA_Value,
CASE 
    WHEN t1.ContractType != t2.LeaseType THEN CAST(LeaseType as VARCHAR)
    WHEN t1.[Address] != t2.AddressMain THEN CAST(AddressMain as VARCHAR)
    ELSE 'N/A' END as SystemB_Value
FROM Table1 as t1 
INNER JOIN Table2 as t2
ON t1.ContractNo = t2.ContractNumber
WHERE t1.ContractType != t2.LeaseType
OR t1.[Address] != t2.AddressMain
BTW你看过Redgate的SQL Compare吗? http://www.red-gate.com/products/sql-development/sql-comparison-sdk/