Pergunta

I have to query a set of running total data by month.

e.g. 
Month                 Amount            Total
2014-01-01            100               100
2014-01-02            100               200
2014-01-03            100               300

The application does not allow to create a view or SP. It is able to select data from a table directly.

e.g.
select Month,
       Amount, 
       Total -- This is my problem.
from   Table -- This is a table only.

Any ideas are welcome, thank you.

Foi útil?

Solução

You can use OUTER APPLY:

SELECT  T.Month,T.Amount,T2.Total
FROM    Table1  T
        OUTER APPLY
        (   SELECT  Total = SUM(Amount)
            FROM    Table1  T2
            WHERE   T2.Month  <= T.Month 
        ) T2;

Or a correlated subquery:

SELECT  T.Amount, 
        (   SELECT  Amount = SUM(Amount)
            FROM    Table1 T2
            WHERE   T2.Month <= T.Month 
        ) 
FROM    Table1 T

Outras dicas

The easiest way is to use SQL Server 2012 because it has cumulative sum built-in:

select Month, Amount, 
       sum(Amount) over (order by Month) as Total -- This is my problem.
from Table; 

The correlated subquery method follows a similar structure:

select Month, Amount,
       (select sum(Amount) from table t2 where t2.Month <= t.Month) as Total
from Table t;

These are usually the two methods that I would consider, because both are standard SQL. As Vignesh points out you can do it with cross apply as well (although as I write this, his query is not correct).

Here is a second way to create a running total:

SELECT t.month, t.amount, 
SUM(t.amount) OVER(PARTITION BY t.month ORDER BY t.month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as [Total]
FROM [yourTable] AS t
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top