2012-09-18 35 views
1

我正在嘗試創建一個查詢以列出所有(美國)狀態在連接系列中的計數,以便它爲表中定義的所有狀態顯示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專家,這真的是給我找麻煩。有人會對我做錯什麼有所瞭解嗎?

回答

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

+0

這是驚人的,我一直在掙扎了一整天。如果可以的話,是否有可能解釋我做錯了什麼? – asawyer

+0

@asawyer因爲你使用的是INNER JOIN,它正在尋找所有表中匹配的記錄,但我們也試圖返回缺失的記錄,所以你需要一個'LEFT JOIN'。同樣在COUNT()上,我切換到使用'cr.PolType'而不是's.StateNum',因爲它會始終返回至少爲'1',因爲該數字從第一個表中存在。所以我把它改成了COUNT()這個可能會丟失的字段。 – Taryn

+0

@asawyer如果你刪除了'count()','GROUP BY'和'SELECT *',你可以查看'INNER'和'LEFT JOIN'都返回的數據。 – Taryn