Tuesday 1 May 2012

Query To Find Running Total In Mysql

This is the sample table to find running total in mysql

CREATE TABLE `runningtotal` (
  `Id` int(11) NOT NULL ,
  `Amount` decimal(10,2) DEFAULT NULL,
  `Date` date DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Sample Data:
Id      Amount          Date
1       1000.00          01/05/2012
2       340.00            01/05/2012
3       1200.00          01/05/2012
4       323.00            02/05/2012
5       560.00            02/05/2012
6       3400.00          03/05/2012
7       1000.00          04/05/2012
8       1000.00          04/05/2012

Query :

set @runtot:=0;
 select DATE_FORMAT(q1.DATE,'%D%M%Y'),q1.Amount,(@runtot := @runtot + q1.Amount) AS TurnOver 
 from 
 (SELECT Date,Sum(AMOUNT) as Amount, COUNT(*) AS C
 FROM runningtotal 
 group by Date) as q1 

Result:

Date               MonthYear    Total TurnOver
1stMay2012   2540.00         2540.00
2ndMay2012 883.00            3423.00
3rdMay2012  3400.00         6823.00
4thMay2012  2000.00         8823.00

No comments:

Post a Comment