To display the running totals is a usual request, and there is no direct and easier way then this to do so in SQL.
The purpose to use SQL to display running totals is similar to displaying rank: first we have to self-join, then, list out the results in order.
Where as finding the rank requires doing a count on the number of records that's listed ahead of the record of interest, finding the running total requires summing the values for the records that's listed ahead of the record of interest.
Name Sales
Himanshu 10
Manish 15
Prateek 20
Mayank 40
Suresh 50
Mohan 20
We want the cumilative sum of the table based on the total sale being made.
SELECT a1.Name, a1.Sales, SUM(a2.Sales) Running_Total
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;
Name Sales Running_Total
Himanshu 50 50
Manish 40 90
Prateek 20 110
Mayank 20 130
Suresh 15 145
Mohan 10 155
0 Comment(s)