首页 > 代码库 > 一个统计以往数据的SQL。

一个统计以往数据的SQL。

今天有一位朋友发了这么个场景:一个商店的收入记录表,每天都有记录;

日期每天收入
07/11100
07/12102
07/13103
07/14101

 

 

 

 

 

现在做一个统计,用户希望看到自已的收入统计

日期每天收入
07/11100
07/12202
07/13305
07/14406

 

 

 

 

 

CREATE TABLE IF NOT EXISTS `income` (  `id` int(11) NOT NULL,  `idate` date DEFAULT NULL,  `money` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `idate` (`idate`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

select a.idate ,sum(b.money) as numfrom income as a left join income as b on b.idate<=a.idate group by a.idate order by a.idate 

 

SELECT id, idate, (@rowNum := @rowNum + money) AS total FROM income, (SELECT (@rowNum := ifnull( (SELECT sum( money ) FROM income WHERE id <=0 ) , 0)))b ORDER BY id limit 0,30