Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL using SUM for a running total

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!

like image 822
luke2012 Avatar asked Aug 16 '12 06:08

luke2012


2 Answers

No join is needed, you can speed up the query this way:

select id, [user], value, total
from
(
  select id, [user], value, 
  row_number() over (partition by [user] order by id desc) rn, 
  sum(value) over (partition by [user]) total
from users
) a
where rn = 1
like image 181
t-clausen.dk Avatar answered Oct 06 '22 01:10

t-clausen.dk


try this:

;with cte as 
     (SELECT a.id, a.[user], a.value, SUM(b.value) AS total
    FROM users a INNER JOIN users b
    ON a.id >= b.id
    AND a.[user] = b.[user]
    GROUP BY a.id, a.[user], a.value
     ),
cte1 as (select *,ROW_NUMBER() over (partition by [user] 
                         order by total desc) as row_num
         from cte)
select  id,[user],value,total from cte1 where row_num=1

SQL Fiddle Demo

like image 45
Joe G Joseph Avatar answered Oct 06 '22 01:10

Joe G Joseph