0

Possible Duplicate:
Calculate a Running Total in SqlServer

I am new to SQL. This question seems very basic but I just couldn't find the answer, maybe I am not hitting the right keyword.

In SQL server 2008 R2 I have a table like this:

Date      Value
---------------
2012-1-1    100
2012-1-2     50
2012-1-4    200

I want to create a view with accumulated value, like this:

Date      Total
---------------
2012-1-1    100
2012-1-2    150
2012-1-4    350

How should I do it?

Community
  • 1
  • 1
NS.X.
  • 2,072
  • 5
  • 28
  • 55
  • 2
    @KenWhite, thanks for the info, it is exactly what I'm looking for. But please do not presume I didn't try searching. As a non-English speaker and new to SQL, I tried every word I could think of including "rollup", "accumulated", "historical sum", etc. I guess since I've realized this, my question should have really been "what is the terminology for [this thingy] in SQL world". – NS.X. Aug 09 '12 at 01:34
  • 1
    You're absolutely correct - I should not have made that presumption. I saw `running-total` in the tag, and made the assumption (and we all know what that means) that you had put it there. My apologies. :-( – Ken White Aug 09 '12 at 01:38

2 Answers2

2

This should get the running total. try this one:

SELECT dateHere,
       total,
       total + COALESCE(
                         (
                            SELECT SUM(total)
                            FROM myTable b
                            WHERE b.dateHere < a.dateHere
                          ), 0) AS RunningTotal
FROM     myTable a
ORDER BY dateHere

SQLFiddle Demo

John Woo
  • 258,903
  • 69
  • 498
  • 492
1

Here is one way to do it with a correlated subquery:

select t.date, t.value,
       (select sum(t2.value)
        from t t2
        where t2.date <= t.date
       ) as cumvalue
from t
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786