mysql - Sum records when counter increases -
i displaying records need sum cost sumcost counter increases particular group of records. appreaciate simple sql code. e.g.
group| items | cost | sumcost| counter ----------------------------------------- cars | opel | 50 | 50 | 1 cars | toyota| 60 | 110 | 2 cars | kia | 40 | 150 | 3 laps | acer | 30 | 30 | 1 laps | hp | 45 | 75 | 2 laps | compaq| 20 | 95 | 3 , on....
want that, e.g. group (cars) displaying records, should sum cost of each car item , display sum/total in sumcost column. sumcost of opel 50, sumcost of toyota (cost of opel , toyota i.e. 50+60=110) , of kia (opel cost + toyota cost + kia cost => 50+60+40=150) etc
here ask, exactly:
select if(t.counter=1, @sum:=0,null) _, @sum:=@sum+t.cost sum, t.* t;
sqlfiddle without counter, group changing
i review question , find useful answer
here same solution sum counting:
select *, (select sum(cost) sometbl counter t.groups = counter.groups , t.id >= counter.id) cost_sum sometbl t
Comments
Post a Comment