R
R
Roman Sokolov2014-08-07 13:22:08
SQL
Roman Sokolov, 2014-08-07 13:22:08

How to get the total value when using running totals?

Task: Calculate running totals for the summa field. Each line should contain the sum of the previous lines without the current value. If you use a window function with parameters:
rows between unbounded preceding and current row
totals are counted, including the current line, so I came to the conclusion that you need to count all lines up to the current one:

select	[id], [data], [summa], 
    sum([summa]) over	(order by [id]
      rows between unbounded preceding and  1 preceding )
    as [Itog]
from	[dbo].[Operations]

In this case, a problem arises: the last total value is missing and I can’t figure out how to get it without bicycles.
For clarity, I will give an answer:
3c1390f367df4af3900bd29e7617d72b.png
The first line contains NULL, because there was nothing to count. There is no last row in the Operations table. But it is somehow obtained from the query and shows the total of the table.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Skahin, 2014-08-07
@pihel

I don’t know how in T-SQL, but in oracle you can do this
1. UNION

select id, sum(summa) over	(order by id rows between unbounded preceding and  1 preceding ) as Itog from [dbo].[Operations]
union all
select NULL, SUM(summa) from [dbo].[Operations]

2. Calculate the grand total in a separate column
select	[id], [data], [summa], 
    sum([summa]) over	(order by [id]
      rows between unbounded preceding and  1 preceding )
    as [Itog],
               sum([summa]) over	( ) as [Itog1]
from	[dbo].[Operations]

3. You can calculate the subtotal without analytical functions (I don’t know how much the performance will change), and form the final line with the rollup function (oracle)
select d1.id, SUM(d2.summa)
from [dbo].[Operations] d1 left join [dbo].[Operations] d2
ON( d1.id > d2.id )
group by rollup(d1.id)
order by d1.id

although the 3rd option counts the amount by subtotals, this is not quite the same amount)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question