I am trying to create a query to list counts for all (US) states in series of joins, so that it shows 0’s for all states defined in a table that does not appear in the rest of the data.
This is what I’ve come up with so far:
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
But I’m still not seeing an records that don’t appear in the rest of the data.
I’ve created a sqlFiddle with the given scema and sample data.
The current output its:
STATENAME STATENUM COUNT
Kentucky 16 14
Ohio 34 4
The desired output would be:
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
I’m not really a SQL expert and this has really been giving me trouble. Would anyone have some insights into what I’m doing wrong?
I made a few changes to your query, including using
LEFT JOINon most of the joins:See SQL Fiddle with Demo