2013-01-31 29 views
1

可能重複:
Calculate a running total in MySQL數與組和由

我需要它爲每個dates.Now的分組數之我正在以下查詢和獲取了放如下:

SELECT `timestamp` , COUNT(*) 
FROM `A` 
WHERE `timestamp` >= '2013-01-04 07:12:12' 
GROUP BY DATE_FORMAT(`timestamp` , '%Y-%m-%d') 

和我得到

OUTPUT:

timestamp            count(*) 
-------------------------------------------------- ----------- 
2013-01-04 07:58:21        4 
2013-01-05 09:28:56        38 
2013-01-06 00:03:04        10 

現在我需要的是,我需要獲得通過日期分組計數的總和。這是第二次約會應該是42,第三次約會應該是52.我如何在查詢中做到這一點?

回答

0

你可以試試下面的SQL

SELECT DATE_FORMAT(ts_date , '%Y-%m-%d') as ts_dt_out, SUM(cnt) 
FROM 
(
SELECT `timestamp` ts_date , COUNT(*) as cnt 
FROM `A` 
WHERE `timestamp` >= '2013-01-04 07:12:12' 
GROUP BY DATE_FORMAT(`timestamp` , '%Y-%m-%d') 
) 
as inner 
WHERE ts_date >= '2013-01-04 07:12:12' 
GROUP BY ts_dt_out 

注:未測試讓我知道,如果它不工作

+0

這可能適用於這種情況,但如果行數更多,如果再過10天,如果Alwin提到的解決方案限制爲3天,我希望他需要動態查詢一個解決方案 – hsuk

0

試試看:

SELECT `timestamp` , @sum:= ifnull(@sum, 0) + COUNT(*) 
FROM `A` 
WHERE `timestamp` >= '2013-01-04 07:12:12' 
GROUP BY DATE_FORMAT(`timestamp` , '%Y-%m-%d') 
0

嘗試:

SELECT 
    timestamp t , 
    (select count(*) from A where timestamp <= t) 
FROM A 
GROUP BY timestamp 
ORDER BY timestamp 
0

這裏是一個簡單的方法

SELECT 
    `timestamp` , 
    COUNT(*) 
FROM `A` 
WHERE `timestamp` >= '2013-01-04 07:12:12' 
GROUP BY DATE(`timestamp`) 
+0

這隻會給count.Not我找的總和 –