Skip to content

Calcular un total acumulado (suma acumulada) snippet

Un total acumulado suma cada fila hasta e incluyendo la actual — el trabajo clásico de una función de ventana, sin self-join ni subconsulta.

Un total acumulado suma cada fila hasta e incluyendo la actual — el trabajo clásico de una función de ventana, sin self-join ni subconsulta. La trampa se esconde en el frame: con ORDER BY dentro de OVER, el frame por defecto es RANGE UNBOUNDED PRECEDING, y RANGE trata las filas empatadas (misma clave de orden) como un solo paso — todas las filas empatadas reciben el mismo total. ROWS UNBOUNDED PRECEDING hace la acumulación fila por fila, que es casi siempre lo que significa un total acumulado. Omite el ORDER BY por completo y obtendrás el total general en cada fila.

Receta ejecutable · 1 lenguajes
Files & Datasqlwindow-functionssumaggregatecumulative

Every language

1 lenguajes, 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 →