如何在 SQL 查询中减去 2 SUM

How to subtract 2 SUM in SQL query

我想查找除退款金额之外的特定项目金额的总未付金额。

根据售出次数,每件商品将有两列,final_amount 和每件商品的第 2 refund_amount,我想从 final_amount 每一项。

PFB code/query

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

我在

附近收到 "SUM" 的语法错误
SUM(final_amount)-SUM(ISNULL(refund_amount, 0)) AS outstanding_amount

我尝试了不同的代码:

SUM(total_amount - total_refund) AS npv

我也遇到了同样的错误。

你少了一个逗号。此外,您应该检查 NULL after the 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

试试这个

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

首先,语法中存在一些错误。您缺少所有 select 元素之间的逗号(在您的 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

您的列“.... AS total_refund”后缺少逗号 (,)。添加逗号,这将解决语法问题。

并且请使用 GROUP BY item_id 而不是 GROUP BY 1