我有一组包含供应商,发票和金额字段的付款数据。单笔付款可以包含多个与之关联的发票。我想获得付款金额,折扣和净付款的总和。我对一次付款的查询效果很好,但对于另一次付款,它会返回与每张发票相对应的单独记录。
期望的结果
当前结果
这是查询
SELECT
Payment,
Vendor,
SUM(Amount) AS AmountTotal,
SUM(Discount) AS DiscountTotal,
SUM(Amount) - SUM(Discount) AS NetPaymentTotal
FROM
PaymentInfo
GROUP BY
Payment, Vendor, Amount, Discount;
我还创建了一个SQL Fiddle来证明这个问题。
付款5000002工作正常,但付款5000005没有。
答案 0 :(得分:2)
从amount
discount
和group by
SELECT
Payment,
Vendor,
SUM(Amount) AS AmountTotal,
SUM(Discount) AS DiscountTotal,
SUM(Amount) - SUM(Discount) AS NetPaymentTotal
FROM
PaymentInfo
GROUP BY
Payment, Vendor;
答案 1 :(得分:0)
当您在amount
子句中包含group by
时,您也会根据account
分隔它。由于amount
与vendor
'5000002'相同,因此vendor
没有区别。与vendor
的{{1}}不同的其他amount
不同,您为每个金额获得两行作为组。
因此,如果您从account
子句中删除group by
,您将获得所需的结果。