如何对计算结果进行分组

How to group the results of a calculation

我有两个 table:dbo.company_data,其中包含不同的公司及其原籍国,第二个 table dbo.sellers_data 其中有这些公司互相出售的单位。

我需要获取的是: a table 由三列组成 - country, export, import,其中包含每个国家的出口(出售给其他国家)和进口(从其他国家购买)商品的价值总和。每个国家都应该出现在这个 table.

您需要使用两个 joins 和聚合函数 sum 聚合进出口单位。

select
  country,
  coalesce(sum(se.units), 0) as export_qty,
  coalesce(sum(si.units), 0) as import_qty
from company_data c

left join seller_data se
on c.company_name = se.seller

left join seller_data si
on c.company_name = si.buyer

group by
  country

尝试这样的事情

  
  SELECT cd.Country, SUM(exports.units) AS export, SUM(imports.units) AS import
  FROM dbo.company_data cd
  LEFT JOIN dbo.sellers_data exports
    ON cd.Country = exports.Seller
  LEFT JOIN dbo.sellers_data imports
    ON cd.Country = imports.buyer
  GROUP BY cd.Country
  ORDER BY cd.Country