Skip to content

Calcular um total acumulado (soma cumulativa) snippet

Um total acumulado soma todas as linhas até à atual inclusive — o trabalho clássico de uma window function, sem self-join e sem subquery.

Um total acumulado soma todas as linhas até à atual inclusive — o trabalho clássico de uma window function, sem self-join e sem subquery. A armadilha esconde-se na frame: com ORDER BY dentro de OVER, a frame por omissão é RANGE UNBOUNDED PRECEDING, e o RANGE trata as linhas empatadas (mesma chave de ordenação) como um único passo — todas as linhas empatadas recebem o mesmo total. ROWS UNBOUNDED PRECEDING faz a acumulação linha a linha, que é quase sempre o que um total acumulado significa. Omita o ORDER BY por completo e obtém o total geral em todas as linhas.

Receita executável · 1 linguagens
Files & Datasqlwindow-functionssumaggregatecumulative

Every language

1 linguagens, copy-ready. One at a time with syntax highlighting, or all inline.

SQLSQLrunnable
SELECT
    day,
    amount,
    SUM(amount) OVER (
        ORDER BY day
        ROWS UNBOUNDED PRECEDING
    ) AS running_total
FROM daily_sales
ORDER BY day;

Try it in the playground: add a duplicate day and watch the RANGE default give both rows the same total; ROWS fixes the accumulation. Moving 7-day window: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW.

Run in the SQL playground →

Keep going

Read the sql-window-functions cheatsheet →