2013-03-04 105 views
0

我試着去顯示0計數,如果計數爲0,例如MYSQL顯示結果即使計數爲0從一個表

CURENT結果:

Extension Calls 
1234   1 
1345   2 

但我希望它顯示:

Extension Calls 
1234   1 
1245   0 
1345   2 

SELECT c.Extension,count(c.Extension),0 as Calls 
from call c 
where c.callType=3 
and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00')) 
group by c.Extension 
+0

是你有一個擴展表,從選擇,'留在擴展JOIN calls',你有你的結果。 – Wrikken 2013-03-04 23:48:36

+4

擴展= 1245是否爲'Calls' NULL? – 2013-03-04 23:49:13

+0

這個數據全部來自一個表 – user2133771 2013-03-04 23:50:46

回答

2

在聯合中的第一個查詢已經可用於在給定時間內具有給定時間的調用的擴展即將到來的問題中。第二個查詢只是將呼叫次數取爲零的情況的否定。

 SELECT c.Extension,count(c.Extension) as Calls 
     from call c 
     where c.callType=3 
     and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00')) 
     group by c.Extension 
    union 
     SELECT c.Extension,0 as Calls 
     from call c 
     where (c.callType=3 
      and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00'))) = false 
     group by c.Extension 
    order by Extension 
+0

小解釋會很棒,所以OP有一些學習經驗。謝謝 :] – 2013-03-05 00:01:14

0
SELECT 
    A.Extension, 
    IFNULL(B.ExtensionCount,0) Calls 
FROM 
(
    SELECT DISTINCT Extension 
    FROM call WHERE callType=3 AND 
    StartTime BETWEEN TIMESTAMP(CURDATE(),'06:30:00') 
    AND TIMESTAMP(CURDATE(),'07:00:00') 
) A 
LEFT JOIN 
(
    SELECT Extension,COUNT(1) ExtensionCount 
    FROM call WHERE callType=3 AND 
    StartTime BETWEEN TIMESTAMP(CURDATE(),'06:30:00') 
    AND TIMESTAMP(CURDATE(),'07:00:00') 
    GROUP BY Extension 
) B 
USING (Extension); 

請確保您有這些指標

ALTER TABLE call ADD INDEX 
callType_StartTime_Extension_ndx (callType,StartTime,Extension); 
ALTER TABLE call ADD INDEX Extension_ndx (Extension); 

這樣,查詢不從表中讀取。它將讀取索引中的所有內容。

0

您可以有條件聚集做到這一點:

SELECT c.Extension, 
     sum(case when c.callType=3 and 
        c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00') 
       then 1 
       else 0 
      end) as calls 
from call c 
group by c.Extension 
相關問題