如何在SQL中使用左JOIN来提取结果?
任务是生成一个摘要,该摘要由每个国家进口和出口的商品价值组成。请注意,当一家公司购买一些商品时,它会导致其国家的总进口,当公司出售某些商品时,它会促成其国家的总出口。
编写由三列组成的退货表的SQL查询:国家,进出口,进口,其中包含每个国家的出口和进口商品价值的总和。每个国家都应出现在此表中,结果应按国家越来越多地排序。
两个表如下:
查询应返回:
假设:
- 单个国家内的公司之间没有贸易。
- 餐桌交易中的每个公司也出现在餐桌公司中。
- 每个公司都完全出现在餐桌公司中一次。
我尝试了以下查询,但没有返回正确的结果,如上所述。
SELECT cd.country, SUM(exports.value) AS export, SUM(imports.value) AS import
FROM companies cd
LEFT JOIN trades exports
ON cd.country= exports.seller
LEFT JOIN trades imports
ON cd.country = imports.buyer
GROUP BY cd.country
ORDER BY cd.country
The task is to generate a summary that consists of sums of the value of goods imported and exported by every country. Note that when a company buys some goods, it contributes to its country's total import, and when the company sells some goods, it contributes to its country's total export.
Write SQL query that return table consisting of three columns: country, export, import, which contain the sums of the values of the exported and imported goods for every country. Each country should appear in this table and result should be sorted increasingly by country.
Two tables are as follows:
The query should return:
Assume that:
- There is no trade between companies within a single country.
- Every company in table trades also appears in table companies.
- Every company appears in table companies exactly once.
I have tried the following query but it isn't returning the correct result as shown above.
SELECT cd.country, SUM(exports.value) AS export, SUM(imports.value) AS import
FROM companies cd
LEFT JOIN trades exports
ON cd.country= exports.seller
LEFT JOIN trades imports
ON cd.country = imports.buyer
GROUP BY cd.country
ORDER BY cd.country
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个简单的解决方案是分别计算出口并将其组合在一起:
A simple solution is calculate exports and imports separately and combine them: