Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top