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