T-SQL using SUM for a running total

Viewed 15885

I have a simple table with some dummy data setup like:

|id|user|value|
---------------
 1  John   2
 2  Ted    1
 3  John   4
 4  Ted    2

I can select a running total by executing the following sql(MSSQL 2008) statement:

SELECT a.id, a.user, a.value, SUM(b.value) AS total
FROM table a INNER JOIN table b
ON a.id >= b.id
AND a.user = b.user
GROUP BY a.id, a.user, a.value
ORDER BY a.id

This will give me results like:

|id|user|value|total|
---------------------
 1  John   2     2
 3  John   4     6
 2  Ted    1     1
 4  Ted    2     3

Now is it possible to only retrieve the most recent rows for each user? So the result would be:

|id|user|value|total|
---------------------
 3  John   4     6
 4  Ted    2     3

Am I going about this the right way? any suggestions or a new path to follow would be great!

5 Answers
Related