如何获得每个独特“列”的SUM()?

时间:2011-10-26 13:39:06

标签: mysql sql

我有这些SQL表

供应商

 SUPPLIERID | SUPPLIERNAME
 1          | sup1
 2          | sup2
 3          | sup3

已售出

ITEMID | SOLD | SUPPLIER ID | DATE
pen    | 10   | 1           | 2011-10-21
pen    | 5    | 1           | 2011-10-22
pen    | 5    | 1           | 2011-10-23
pen    | 20   | 3           | 2011-10-24

 ITEMID | BOUGHT | SUPPLIER ID | DATE
 pen    | 20     | 1           | 2011-9-21
 pen    | 5      | 3           | 2011-9-24

我目前正在使用这个脚本,但它似乎不起作用,因为售出和购买的SUM()增加了三倍。我怀疑原因是因为已售出3排,但只买了2排。知道如何解决这个问题吗?

   SELECT suppliername, SUM(sold) as sold, SUM(bought) AS bought
     FROM sold s
LEFT JOIN supplier sp
       ON s.supplierid = sp.supplierid
LEFT JOIN bought b
       ON sp.supplierid = b.supplierid
 GROUP BY suppliername

2 个答案:

答案 0 :(得分:3)

SELECT suppliername, Sold, Bought
FROM Supplier sp
LEFT JOIN (SELECT SupplierId, SUM(Sold) Sold
           FROM sold
           GROUP BY SupplierId) s
ON sp.SupplierId = s.SupplierId
LEFT JOIN (SELECT SupplierId, SUM(bought) bought
           FROM bought
           GROUP BY SupplierId) b
ON sp.SupplierId = b.SupplierId

基本上,我正在做的是分别计算每个供应商的销售金额和购买金额(LEFT JOIN s),所以我总是有销售总额和购买总金额。我在LEFT JOIN中使用的查询称为派生表,因为它们就像一般查询中的表一样。希望这有助于您更清楚地了解我的所作所为。

答案 1 :(得分:1)

根据给定的数据,我希望看到供应商1的结果增加两倍,供应商2没有返回,供应商3的数量正确。这是因为您隐含地将每个供应商的每个结果从销售中链接到每个供应商购买的每一个结果。

相反,请尝试:

select supplierid, max(suppliername) suppliername, sum(bought) bought, sum(sold) sold
from (
    select supplierid, suppliername, 0 bought, 0 sold from supplier union all
    select supplierid, '' suppliername, bought, 0 sold from bought union all
    select supplierid, '' suppliername, 0 bought, sold from sold) ilv
group by supplierid;