我正在尝试创建一个查询以列出一系列连接中所有(美国)状态的计数,以便它为未出现在其余数据中的表中定义的所有状态显示 0。
到目前为止,这是我想出的:
SELECT s.StateName,s.StateNum, COUNT(s.StateNum) as [count]
FROM States AS s
INNER JOIN StateIncludeInClueReport as scr ON scr.statenum = s.StateNum
LEFT JOIN Staging_Policy sp ON CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)) = s.StateNum
left JOIN (SELECT MIN(sip.QuoteId)AS QuoteId,sip.rmId FROM Staging_Policy sip GROUP BY sip.RMID) as sq ON sq.QuoteId = sp.QuoteID
INNER JOIN dbo.ResultMaster AS rm ON rm.rmID = sq.RMID
INNER JOIN dbo.CreditReport AS cr ON rm.rmID = cr.rmID AND cr.PolType = 'AUTO 3.0'
GROUP BY CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)), s.StateName, s.StateNum
ORDER BY s.StateNum
但我仍然没有看到其他数据中没有出现的记录。
我用给定的 scema 和示例数据创建了一个 sqlFiddle。
电流输出:
STATENAME STATENUM COUNT
Kentucky 16 14
Ohio 34 4
所需的输出将是:
STATENAME STATENUM COUNT
Arkansas 3 0
Georgia 10 0
Indiana 13 0
Kentucky 16 14
Missouri 24 0
Ohio 34 4
Tennessee 41 0
Texas 42 0
Virginia 45 0
我不是真正的 SQL 专家,这确实给我带来了麻烦。有人会对我做错了什么有一些见解吗?