如何在SQL查询中减去2 SUM

时间:2019-04-30 00:29:22

标签: sql sql-server ddp

我想查找特定商品的未偿还总额(退款金额除外)。

根据商品的销售次数,每个商品都会有两列,分别是final_amount和第二个refund_amount,我想从{{1 }}。

PFB代码/查询

refund_amount

我在

附近收到“ SUM”的语法错误
final_amount

我尝试了不同的代码:

SELECT item_id,
       SUM(final_amount) as total_amount,
       SUM(ISNULL(refund_amount, 0)) AS total_refund
       SUM(final_amount) - SUM(ISNULL(refund_amount, 0)) AS outstanding_amount                    
FROM tabel1 
WHERE item_id in ('119688521',
                  '109536343',
                  '99459466',
                  '97126817',
                  '138148320',
                  '107816131')
GROUP BY 1

我也遇到同样的错误。

4 个答案:

答案 0 :(得分:1)

首先,语法上有一些错误。您在所有选择元素之间(在total_refundoutstanding_amount之间)都缺少逗号。您还应该检查SUM()是否为空,而不是列是否为空。如果愿意,也可以使用COALESCE()。最后,您需要GROUP BY,例如item_id

SELECT item_id,
       SUM(final_amount) as total_amount,
       ISNULL(SUM(refund_amount), 0) AS total_refund,
       SUM(final_amount) - ISNULL(SUM(refund_amount), 0) AS outstanding_amount
FROM tabel1 WHERE item_id in ('119688521',
                              '109536343',
                              '99459466',
                              '97126817',
                              '138148320',
                               '107816131')

GROUP BY item_id

答案 1 :(得分:0)

您缺少逗号。此外,您应该在NULL之后检查SUM()

SELECT item_id,
       SUM(final_amount) as total_amount,
       COALESCE(SUM(refund_amount), 0) AS total_refund,
       (SUM(final_amount) - COALESCE(SUM(refund_amount), 0)
       )  AS outstanding_amount
FROM tabel1
WHERE item_id in ('119688521', '109536343', '99459466', '97126817', '138148320', '107816131')
GROUP BY 1

答案 2 :(得分:0)

尝试一下

SELECT item_id,
SUM(final_amount) as total_amount,
SUM(ISNULL(refund_amount, 0)) AS total_refund

SUM(final_amount - isnull(refund_amount, 0)) AS outstanding_amount

FROM tabel1 WHERE item_id in ('119688521',
'109536343',
'99459466',
'97126817',
'138148320',
'107816131')

GROUP BY item_id

答案 3 :(得分:0)

您不希望在“ .... AS total_refund”列后面加上逗号(,)。添加逗号,这将解决语法问题。

请使用GROUP BY item_id代替GROUP BY 1