为什么我的SQL SUM为我的加入赢了?

时间:2015-01-25 06:47:33

标签: sql select sum inner-join

所以我有代码将所有供应商的付款汇总在一起,然后将其显示在降序列表中。

SELECT vendor_name, SUM(payment_total) AS payment_total
FROM Vendors  JOIN Invoices
     ON (Vendors.vendor_id = Invoices.vendor_id)
GROUP BY vendor_name, payment_total
ORDER BY payment_total DESC;

然而,它所做的只是将供应商名称列表与重复列出的付款总额列入而不是加起来。我尝试使用DISTINCT,但仍然得到相同的结果。

2 个答案:

答案 0 :(得分:1)

删除GROUP BY payment_total,因为您希望按供应商分组的总数:

SELECT 
    vendor_name, 
    SUM(payment_total) AS payment_total
FROM 
    Vendors  
    JOIN Invoices ON Vendors.vendor_id = Invoices.vendor_id
GROUP BY 
    vendor_name
ORDER BY 
    SUM(payment_total) DESC

并按SUM(payment_total) DESC

排序

答案 1 :(得分:1)

您希望将每个供应商名称的总和加起来,而不是按当前group by子句指示的每个供应商名称和总计。只需从中移除total_payment,您就可以了:

SELECT   vendor_name, SUM(payment_total) AS payment_total
FROM     Vendors 
JOIN     Invoices ON (Vendors.vendor_id = Invoices.vendor_id)
GROUP BY vendor_name
ORDER BY payment_total DESC;