简体   繁体   中英

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

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

Is this possible in 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

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 ,

fiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM