TSQL多JOIN问题:Northwind库中国家统计结果不符预期
问题分析与解决
错误原因
你的第二个LEFT JOIN关联条件写错了:你用了sc.Country=cc.Country,但对于阿根廷这种没有供应商的国家,第一个左连接后sc.Country的值是NULL,而CustomerCountry里阿根廷的Country是Argentina,NULL和任何值都不相等,所以这个关联匹配不到数据,最终cc.TotalCustomers就是NULL,经过ISNULL处理后就变成0了。
修正后的查询语句
把第二个左连接的关联条件改成用主表CountryList的Country去关联CustomerCountry的Country,也就是把sc.Country=cc.Country换成cl.Country=cc.Country:
USE Northwind GO WITH CountryList AS (SELECT Country FROM Customers UNION SELECT Country FROM Suppliers), SupplierCountry AS (SELECT Country, TotalSuppliers=COUNT(*) FROM Suppliers GROUP BY Country), CustomerCountry AS (SELECT Country, TotalCustomers=COUNT(*) FROM Customers GROUP BY Country) SELECT cl.Country, ISNULL(sc.TotalSuppliers,0) TotalSuppliers, ISNULL(cc.TotalCustomers,0) TotalCustomers FROM CountryList cl LEFT JOIN SupplierCountry sc ON cl.Country=sc.Country LEFT JOIN CustomerCountry cc ON cl.Country=cc.Country -- 修改此处的关联条件
验证结果
修正后,阿根廷的结果会符合预期:
Country TotalSuppliers TotalCustomers Argentina 0 3
内容的提问来源于stack exchange,提问作者Michael Shuv
相关产品推荐
相关产品推荐

