2017-08-03 49 views
0

我是mySQL的新手,主要從事一個初始表的查詢工作,並在兩個單獨的表中總結其內容。第二個「摘要」表是丟棄值爲0的元組;我需要解決這個問題。以下是具體情況:mySQL - 如何保持count()函數不會丟失0個計數?

我有一個大的庫存表,這是我從其他表組裝:

SID CID SECTION RATING 
========================== 
100 1001 1  A 
101 1001 1  A 
102 1002 1  B 
103 1002 2  F 
104 1003 1  A 
...etc... 

(「CID」和「節」是這裏的主鍵,我不知道是否PK分佈在兩個屬性在這裏很重要。)我有一個成功的查詢(「numTable1」),它計算每個CID和Section的SID數量。例如,上述庫存表, 「sumTable1」 將是:

CID SECTION numSID 
===================== 
1001 1  2 
1002 1  1 
1002 2  1 
1003 1  1 
...etc... 

這裏的SQL:

create temporary table numTable1(
    SELECT ot1.cid, ot2.section, count(ot1.sid) 'numSID' 
    FROM otherTable1 ot1, otherTable2 ot2 
    WHERE ot1.cid=ot2.cid and ot1.section=ot2.section 
    GROUP BY ot1.cid, ot2.section 
); 

「NumTable」 的偉大工程。問題如下:我還需要一個查詢,它可以計算每個CID /部分的「A」評分數:

create temporary table numA(
    select t9.cid, t9.section, count(ot1.rating) 'As' 
    from otherTable1 ot1, t9 
    where grade = 'A' and t9.cid=ot1.cid and t9.section=ot1.section 
    group by t9.cid, t9.section 

);

這裏的 「NUMA」 的輸出:

CID SECTION As 
===================== 
1001 1  2 
1003 1  1 
...etc... 

但這裏的問題;一些CID /部分沒有A評級,他們正在被淘汰。我需要的是這樣的:

CID SECTION As 
===================== 
1001 1  2 
1002 1  0 
1002 2  0 
1003 1  1 
...etc... 

你會注意到,上表中可以用「numTable1」,這是最終的目標在這裏完美融合:

CID SECTION numSID As 
========================== 
1001 1  2  2 
1002 1  1  0 
1002 2  1  0 
1003 1  1  1 

但只要「NUMA 「將CID /分段下降爲0,我死在水中。我假設我在「numA」中的「group by」語句正在清除零點......但我不確定這一點。有什麼建議麼?

+0

對我來說不是很清楚你想從最後一個表中刪除as = 0的行嗎? – scaisEdge

+0

您必須將您的計數加入基礎數據,以便使用0計數記錄進行充實。 –

+0

查看左連接的查詢 –

回答

0

@NigelRen提供瞭解決方案 - 左連接。代碼如下:

-- Left Join on numTable1 with numA... makes for total students // numAs 
-- Resultant table is totA: "Total A Ratings" 
create temporary table totA(
    select numTable1.cid, numTable19.section, numTable1.numStudents, if(numA.As is null, 0, numA.As) 'A Ratings' 
    from numTable1 
    left join numA on numTable1.cid=numA.cid and numTable1.section=numA.section 
);