如何为SQL Server编写连接查询?

时间:2018-05-16 19:07:31

标签: sql sql-server

我有两个表source_producttarget_product,如下所示:

source_product

pitem_id    prev_id citem_id    crev_id qty     check_no    status
-------------------------------------------------------------------
AAA         null    null        null    null    null        null
AAA         A       Item_2      B       2       100         No
AAA         A       Item_3      A       1       100         No

target_product

pitem_id    prev_id citem_id    crev_id qty     check_no    status
-------------------------------------------------------------------
null        null    null        null    null    null        null
AAA         A       Item_2      B       2       100         No
AAA         A       Item_3      A       3       110         Yes

我需要的结果是比较source_producttarget_product表,并将差异放在final_product表中,如下所示:

Final_product

pitem_id    prev_id citem_id    crev_id Validation_error    validation_column   Source_value    target_value
-------------------------------------------------------------------------------------------------------------
AAA         A       null        null    pitemid ,prev_id not found in target    null    null    null
AAA         A       Item_2  B   citemid ,crev_id not found in target            
AAA         A       Item_3  A   qty mismatch    qty 1   3
AAA         A       Item_3  A   check_no mismatch   cheeck_no   100 110
AAA         A       Item_3  A   status mismatch status  No  Yes

如何编写此查询?我尝试使用union all,但是我得到了重复数据和不正确的数据。

2 个答案:

答案 0 :(得分:0)

union只是将具有相同格式的多个结果集(输出)组合到一个聚合输出中。您希望在生成单个输出之前组合多个imput并进行处理,因此您需要的是join。您可以按照此类模板获得所需的结果:

SELECT
    sourceProduct.*,
    targetProduct.*,
    -- go column by column to determine what matches
    CASE
        WHEN
            (sourceProduct.SomeColumn1 IS NULL AND targetProduct.SomeColumn1 IS NULL)
            OR sourceProduct.SomeColumn1 = targetProduct.SomeColumn1
        THEN 1
        ELSE 0
    END AS SomeColumn1Matches
    -- keep going as needed
FROM
    SourceProduct sourceProduct
    INNER JOIN TargetProduct targetProduct
        ON sourceProduct.pitem_id = targetProduct.pitem_id -- assumes a full bijection between tables

您可以调整查询以格式化结果和检查以及所需的内容。如果您的源和目标产品表在其ID之间没有广告素材,那么您需要查看FULL OUTER JOIN而不是INNER JOIN

答案 1 :(得分:0)

可以做这样的事情。你必须调整我认为的语法/括号,但这个想法应该是显而易见的。

SELECT 'Source' AS disposition,
       srcEtgt.*
  FROM (SELECT * 
          FROM source
        EXCEPT
        SELECT * 
          FROM target
       ) srcEtgt
 UNION
SELECT 'Target' AS disposition,
       tgtEsrc.*
  FROM (SELECT * 
          FROM target
        EXCEPT
        SELECT * 
          FROM source
       ) tgtEsrc