2012-11-05 115 views
3
的總和

可能重複:
MySQL Count data for last 7 days獲取領域

我有,我需要展示場之和的問題。可以說我有一個記錄如下,

detectDate  |isp |infection | count 
-------------------------------------- 
2012-10-02 01:00|aaaa |malware |3 
2012-10-02 01:30|bbbb |malware |2 
2012-10-02 01:33|bbbb |spy-eye |2 
2012-10-02 01:45|aaaa |DDos  |1 
2012-10-03 01:50|cccc |malware |2 
2012-10-03 02:00|dddd |TDSS  |2 
2012-10-03 04:50|dddd |TDSS  |3 

,我想顯示的輸出,它會顯示每一天所有感染的總和如下,

detectDate |infection | count 
------------------------------- 
2012-10-02 |DDos  |1 
2012-10-02 |malware |5 
2012-10-02 |spy-eye |2 
2012-10-02 |TDSS  |0 
2012-10-03 |DDos  |0 
2012-10-03 |malware |2 
2012-10-03 |spy-eye |0 
2012-10-03 |TDSS  |5 

我用這個查詢,

SELECT DATE_FORMAT(detectDate, '%Y-%m-%d') AS detectDate, infection, SUM(count) 
FROM `tbl_correlateddata` 
GROUP BY DATE_FORMAT(detectDate, '%Y-%m-%d') , infection 

但它只如下是我的要求給出了把..

detectDate |infection | count 
------------------------------- 
2012-10-02 |DDos  |1 
2012-10-02 |malware |5 
2012-10-02 |spy-eye |2 
2012-10-03 |malware |2 
2012-10-03 |TDSS  |5 

任何幫助將非常有幫助:) 非常感謝你:)感激:)

編輯: 可能重複的:MySQL Count data for last 7 days

但不相似

+0

你正好有所有可能感染的表? – AndreKR

+0

以及一個感染可以發生在一個日期和相同的感染可能不會出現在第二天..這就是爲什麼它是0 n謝謝你的答覆 –

+0

ohh yeaa ..感謝您指向我的帖子..有點相同:) –

回答

7
SELECT e.*, COALESCE(SUM(d.`count`),0) `SUM of count` 
FROM 
(
    SELECT c.detectDate, a.infection 
    FROM 
    (
     SELECT DISTINCT infection 
     FROM tbl_correlateddata 
    ) a CROSS JOIN 
    (
     SELECT DISTINCT DATE(detectDate) detectDate 
     FROM tbl_correlateddata 
    ) c 
) e LEFT JOIN tbl_correlateddata d 
    ON DATE(d.detectDate) = e.detectDate AND 
     d.infection = e.infection 
GROUP BY detectDate, infection 
ORDER BY e.detectDate, e.infection 

SELECT DATE_FORMAT(e.detectDate, '%Y-%m-%d'), 
     e.infection, 
     COALESCE(SUM(d.`count`),0) `SUM of count` 
FROM 
(
    SELECT c.detectDate, a.infection 
    FROM 
    (
     SELECT DISTINCT infection 
     FROM tbl_correlateddata 
    ) a CROSS JOIN 
    (
     SELECT DISTINCT DATE(detectDate) detectDate 
     FROM tbl_correlateddata 
    ) c 
) e LEFT JOIN tbl_correlateddata d 
    ON DATE(d.detectDate) = e.detectDate AND 
     d.infection = e.infection 
GROUP BY e.detectDate, e.infection 
ORDER BY e.detectDate, e.infection 
+0

一樣..謝謝你的答案:)但小編輯,我需要'SUM的計數'字段.. :)和它的工作,:)我可以知道如何得到0爲那些給null時,當你使用null或做我必須通過我的後端應用程序? –

+1

@Hasitha更新。加了'COALESCE'。 –

+1

哦..非常感謝你..你是一個拯救生命..很欣賞:) –