Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2003-11-04 : 07:13:07
|
Chris writes "Thanks for the article on running totals, it's put me on the right track. However, how do you go about calculating a running total for a parameter range. For example, the running total for this:SELECT a.DayCount, a.Sales, SUM(b.Sales) AS RunningTotal, a.otherFROM Sales aCROSS JOIN Sales bWHERE (b.DayCount <= a.DayCount)GROUP BY a.DayCount,a.Sales, a.otherORDER BY a.DayCount,a.SalesDayCount Sales RunningTotal -------- --------------------- --------------------- 1 120.0000 120.00002 60.0000 180.00003 125.0000 305.00004 40.0000 345.00005 10.0000 355.00006 25.0000 380.00007 40.0000 420.00008 55.0000 475.00009 70.0000 545.000010 85.0000 630.000011 100.0000 730.000012 115.0000 845.000013 130.0000 975.000014 145.0000 1120.0000 retrieves the running total (cumulative) for all records. What if I only wanted the records from DayCount 6 to DayCount 12? E.g.DayCount Sales RunningTotal -------- --------------------- --------------------- 6 25.0000 380.00007 40.0000 420.00008 55.0000 475.00009 70.0000 545.000010 85.0000 630.000011 100.0000 730.000012 115.0000 845.0000 returns the running total for all records but restricts it to the range specified. How do I calculate the running total starting from the first in the range specified?" |
|
|
AndrewMurphy
Master Smack Fu Yak Hacker
2916 Posts |
Posted - 2003-11-04 : 07:44:28
|
| surely that's a display issue....however why not wrap the first code with something like.....select * from (SELECT a.DayCount,a.Sales,SUM(b.Sales) AS RunningTotal, a.otherFROM Sales aCROSS JOIN Sales bWHERE (b.DayCount <= a.DayCount)GROUP BY a.DayCount,a.Sales, a.otherORDER BY a.DayCount,a.Sales) cwhere c.daycount > 5order by c.daycount |
 |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2003-11-04 : 07:47:12
|
| [code]WHERE (b.DayCount <= a.DayCount) AND a.DayCount between 6 and 12 AND b.DayCount between 6 and 12[/code] |
 |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2003-11-04 : 08:04:50
|
| And, as always: if you are doing this just to display as a column in a report, I HIGHLY recommend calculating it at the presentation layer on the report itself instead of in SQL. The only time you should be doing running totals in SQL is if further calculations with SQL depend on those running totals. (i.e., calculating taxes up to a YTD ceiling or something like that)It is much easier and more efficent to have a reporting tools like Crystal or even ASP calculate running totals rather than to force SQL Server to.- Jeff |
 |
|
|
|
|
|
|
|