开发者社区> 问答> 正文

SQL Server如何比较2个表以提取差异

到目前为止,我所做的识别不正确付款的操作是运行不正确的查询并检索从12/01/2019开始的所有记录,然后将这些记录保存在临时表中。

使用不正确的表进行查询:

SELECT DISTINCT
    CAST(P.ExternalId AS CHAR(25)) AS 'transID'
,   CASE RTP.Activity 
        WHEN 0 THEN 'Payment' 
        WHEN 1 THEN 'Void' 
    END AS 'transType'
,   P.TransactionCreateDate AS 'createdDate'
,   P.Amount AS 'paymentAmount'             <<< Payment column was being retrieved from wrong table.
,   P.EffectiveDate AS 'paymentDate'
,   CAST(P.Id AS NVARCHAR(50)) AS 'payment_Id'
,   P.TransactionBatchId AS 'batchId'
,   T.TenderTypeId AS 'TenderType'
,   CAST(TType.Name AS CHAR(10)) AS 'PaymentType'
FROM 
    Payments P
INNER JOIN dbo.Tenders T
    ON T.TransactionId = P.TransactionId
INNER JOIN dbo.TenderTypes TType
    ON TType.Id = T.TenderTypeId
WHERE 
    CAST(P.TransactionCreateDate AS DATE) >= '12/01/2019'
ORDER BY 
    createdDate DESC

然后,我对查询进行更正,以检索从2019年12月1日开始的所有交易,但这次获得分类付款,并将其放入第二个临时表中。差异是955条记录。

使用正确的表格查询以获取付款金额:

SELECT DISTINCT
    CAST(P.ExternalId AS CHAR(25)) AS 'transID'
,   CASE RTP.Activity 
        WHEN 0 THEN 'Payment' 
        WHEN 1 THEN 'Void' 
    END AS 'transType'
,   P.TransactionCreateDate AS 'createdDate'
,   T.Amount AS 'paymentAmount'
,   P.EffectiveDate AS 'paymentDate'
,   CAST(P.Id AS NVARCHAR(50)) AS 'payment_Id'
,   P.TransactionBatchId AS 'batchId'
,   T.TenderTypeId AS 'TenderType'
,   CAST(TType.Name AS CHAR(10)) AS 'PaymentType'
FROM 
    Payments P
INNER JOIN dbo.Tenders T
    ON T.TransactionId = P.TransactionId
INNER JOIN dbo.TenderTypes TType
    ON TType.Id = T.TenderTypeId
WHERE 
    CAST(P.TransactionCreateDate AS DATE) >= '12/01/2019'
ORDER BY 
    createdDate DESC

我的问题是,现在如何比较每个表的内容,以提取需要更正的内容?我确信这并不困难,我不知所措,无法弄清楚,想知道是否有人可以伸出援手。

非常感谢

展开
收起
祖安文状元 2020-01-03 18:50:30 660 0
1 条回答
写回答
取消 提交回答
  • EXCEPT接线员会解决您的问题吗?

    SELECT A.a, A.b, ... 
    FROM Table A  
    EXCEPT  
    SELECT B.a, B.b, ... 
    FROM Table B;
    

    Doc在这里:https : //docs.microsoft.com/zh-cn/sql/t-sql/language-elements/set-operators-except-and-intersect-transact-sql?view= sql-server- ver15

    2020-01-03 18:50:51
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载