[英]Mysql - Is it possible to cumlatively sum the previous row values
I have been trying this for a while but no success. 我已经尝试了一段时间,但没有成功。
My database is something like this 我的数据库是这样的
-----------------------------------------------------
DEVICE_HASH | DEVICE_NAME | DEVICE_VERISON | DATE
-----------------------------------------------------
122138223823| crespo | 1.1 | 12/01/13
122138213823| jewell | 1.2 | 12/01/13
122138223823| crespo | 1.1 | 13/01/13
122138263823| crespo | 1.1 | 13/01/13
122138283823| blade | 1.2 | 13/01/13
122138293823| crespo | 1.1 | 14/01/13
-----------------------------------------------------
To get the count on devices downloaded per day i executed the below query which worked fine. 为了获得每天下载设备的数量,我执行了以下查询,效果很好。
SELECT DATE_FORMAT(DATE, '%Y-%m-%d') as 'date', DEVICE_NAME as 'device' ,COUNT(*) as 'count' FROM table_name GROUP BY DATE_FORMAT(DATE, '%Y-%m-%d'), DEVICE_NAME
Eg: I got crespo count as 1 on 12/01/13, 2 on 13/01/13 and 1 on 14/01/13 例如:我在12/01/13上的crespo计数为1,在13/01/13上的计数为2,在14/01/13上的计数为1
Now i want to get the running count of devices ie add previous day value to current day download and go on until the end. 现在,我想获取设备的运行计数,即将前一天的值添加到当前一天的下载中,并继续进行到最后。
Eg: crespo count should go as 1 on 12/01/13, 3 on 13/01/13 and 4 on 14/01/13 例如:crespo计数应在12/01/13时为1,在13/01/13时为3,在14/01/13时为4
Is this possible in mysql ? 在mysql中这可能吗?
I think this is what you're looking for: 我认为这是您要寻找的:
SELECT
@runningTotal:=IF(@prevDevice=Device_Name,@runningTotal+cnt,cnt) rt,
dt, Device_Name, cnt,
@prevDevice:=Device_Name
FROM (
SELECT
DATE_FORMAT(DATE, '%Y-%m-%d') as dt,
DEVICE_NAME ,
COUNT(*) as cnt
FROM table_name
GROUP BY DATE_FORMAT(DATE, '%Y-%m-%d'), DEVICE_NAME
ORDER BY DEVICE_NAME, 2
) t
JOIN (SELECT @runningTotal:=0) r
And the sample fiddle: http://sqlfiddle.com/#!2/e3525/1 和示例提琴: http ://sqlfiddle.com/#!2/ e3525/1
Which produces the following results: 产生以下结果:
RT DT DEVICE_NAME CNT
1 2013-01-13 blade 1
1 2014-01-13 crespo 1
3 2013-01-13 crespo 2
4 2012-01-13 crespo 1
1 2012-01-13 jewell 1
try this , 尝试这个 ,
you need extra variable to keep check of count , 你需要额外的变量来保持计数 ,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.