SQL查询量比较

时间:2018-09-05 14:27:20

标签: sql

我有一个Claim表,其中包含索赔额。我需要写一个查询来比较数量是否相同。

SELECT 
    CLAIM_NO, SUM(TRAN_AMOUNT) AS Amount
FROM 
    CLMTABLE
WHERE 
    TRTYPE = 0
GROUP BY 
    CLAIM_NO

UNION ALL

SELECT 
    CLAIM_NO, SUM(TRAN_AMOUNT) AS Amount
FROM 
    CLMTABLE
WHERE 
    TRTYPE <> 0
GROUP BY 
    CLAIM_NO

输出

CLAIM_NO   AMOUNT
-----------------
1234567890 883.00
1234567890 883.00
1234567891 990.00
1234567891 990.00
1234567892 883.00
1234567892 893.00

最后一条记录的金额不一样,我希望能够发现金额不匹配的声明。

谢谢,我们将不胜感激

2 个答案:

答案 0 :(得分:0)

请使用以下查询查找所有此类交易:

SELECT CLAIM_NO,SUM(CASE WHEN TRTYPE=0 THEN ISNULL(TRAN_AMOUNT,0) ELSE 0 END) As Amount,
    SUM(CASE WHEN TRTYPE<>0 THEN ISNULL(TRAN_AMOUNT,0) ELSE 0 END) AS Amount2
FROM CLMTABLE
GROUP BY CLAIM_NO
HAVING SUM(CASE WHEN TRTYPE=0 THEN ISNULL(TRAN_AMOUNT,0) ELSE 0 END) <> SUM(CASE WHEN TRTYPE<>0 THEN ISNULL(TRAN_AMOUNT,0) ELSE 0 END)

答案 1 :(得分:0)

在SUM函数中使用CASE检索不同类型数量之间的差异。

SELECT claim_no, SUM(CASE WHEN trtype = 0 THEN tran_amount
                     ELSE -1*tran_amount
                     END) as delta
FROM clmtable
GROUP BY claim_no