如何获得每个唯一“列”的 SUM()?
我有这些 SQL 表
“Supplier
SUPPLIERID | SUPPLIERNAME
1 | sup1
2 | sup2
3 | sup3
Sold
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
Bought
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
I have these SQL tables
Supplier
SUPPLIERID | SUPPLIERNAME
1 | sup1
2 | sup2
3 | sup3
Sold
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
Bought
ITEMID | BOUGHT | SUPPLIER ID | DATE
pen | 20 | 1 | 2011-9-21
pen | 5 | 3 | 2011-9-24
I'm currently using this script but it doesn't seem to work as the SUM()
of sold and bought is tripled. I suspect the reason is because there are 3 rows in sold but only 2 in bought. Any idea how to fix this?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,我正在做的是分别计算每个供应商ID的销售量和购买量(在
LEFT JOIN
中),所以我总是有销售总额和购买总额。我在 LEFT JOIN 中使用的查询称为派生表,因为它们的作用类似于一般查询中的表。希望这可以帮助您更清楚地了解我所做的事情。Basically, what I'm doing is calculating the amount sold and the amount bought for every supplierId separately (in the
LEFT JOIN
s), so I always have the total amount sold and total amount bought. The querys that I'm using in theLEFT JOIN
s are called derived tables, since they are acting like a table on the general query. Hope this helps you get a more clear idea of what I did.根据给定的数据,我希望看到供应商 1 的结果增加了两倍,供应商 2 根本没有返回任何内容,供应商 3 的数量也正确。这是因为您隐式地将每个供应商的每个结果从已售出链接到每个结果每个供应商都买了。
相反,请尝试:
From the given data I would expect to see the results for supplier 1 tripled, nothing at all returned for supplier 2 and the right quantity for supplier 3. This is because you are implicitly linking every result for each supplier from sold, to every result from each supplier on bought.
Instead, try: