创建查询以显示具有特定子查询联接的子总计时出现问题

时间:2012-09-18 15:47:30

标签: sql sql-server

我正在尝试创建一个查询来列出一系列连接中所有(US)状态的计数,以便它显示在表中定义的所有状态的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

但我仍然没有看到其他数据中没有出现的记录。

I've created a sqlFiddle with the given scema and sample data.

当前输出:

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专家,这真的给了我麻烦。谁会对我做错了什么有一些见解?

1 个答案:

答案 0 :(得分:2)

我对您的查询进行了一些更改,包括在大多数联接中使用LEFT JOIN

SELECT s.StateName,
  s.StateNum,
  isNull(COUNT(cr.PolType), 0) 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
LEFT JOIN dbo.ResultMaster AS rm 
  ON rm.rmID = sq.RMID
LEFT 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;

请参阅SQL Fiddle with Demo