Create a running total with SQL select statement

Posted on 2006-05-31
Medium Priority
Last Modified: 2006-11-18
I have a set of data in a table which appears as follows

Count    Parent     Child
1           AB20001 TP22226
1           AB20001 TP22258
1           AB20001 TP22252
1           TK55558 TP99562
1           GK88885 CK25996
1           GK88885 CK25996

I would like to create a select statement that will give a result as follows

Count    Parent     Child        Running Total
1           AB20001 TP22226   1
1           AB20001 TP22258   2
1           AB20001 TP22252   3
1           TK55558 TP99562   1
1           GK88885 CK25996   1
1           GK88885 CK25996   2

The addition is the Running total column. This is a running total of the number of instances of the parent code and is being reset on its change. I am unsure of the command that I can use that may be able to achieve this.

Question by:stonehage
  • 2
LVL 143

Accepted Solution

Guy Hengel [angelIII / a3] earned 200 total points
ID: 16797979
select count, parent, child, (select count(*) from yourtable i where i.parent = p.parent and i.child <= p.child ) as r_total
from yourtable p order by p.parent, p.child
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16797980
in sql server 2005, the syntax can be made differently...

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question