You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:45:40