Pergunta

I have the following data in my table:

id   invoice_id   date         ammount
1    1            2012-01-01    100.00
20   1            2012-01-31     50.00
470  1            2012-01-15    300.00

Now, I need to calculate running total for an invoice in some period. So, the output for this data sample should look like this:

id   invoice_id   date         ammount  running_total
1    1            2012-01-01    100.00         100.00
470  1            2012-01-15    300.00         400.00
20   1            2012-01-31     50.00         450.00

I tried with this samples http://www.sqlusa.com/bestpractices/runningtotal/ and several others, but the problem is that I could have entries like id 20, date 2012-01-31 and id 120, date 2012-01-01, and then I couldn't use NO = ROW_NUMBER(over by date)... in first select and then ID < NO in second select for calculating running total.

Foi útil?

Solução

DECLARE @DateStart DATE='2012-01-01'; 

WITH cte 
     AS (SELECT id = Row_number() OVER(ORDER BY [date]), 
                DATE, 
                myid = id, 
                invoice_id, 
                orderdate = CONVERT(DATE, DATE), 
                ammount 
         FROM   [Table_2] 
         WHERE  DATE >= @DateStart) 
SELECT myid, 
       invoice_id, 
       DATE, 
       ammount, 
       runningtotal = (SELECT SUM(ammount) 
                       FROM   cte 
                       WHERE  id <= a.id) 
FROM   cte AS a 
ORDER  BY id 

enter image description here

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top