SQL
SQL Running Total with Window Functions
Calculate cumulative sums or running totals in SQL efficiently using window functions like SUM() OVER() for financial reports, trend analysis, and dashboards.
SELECT
order_date,
total_amount,
SUM(total_amount) OVER (ORDER BY order_date) AS running_total_amount
FROM
daily_sales
ORDER BY
order_date;
How it works: This snippet demonstrates a window function to calculate a running total. SUM(total_amount) OVER (ORDER BY order_date) computes a cumulative sum of total_amount, where each row's running_total_amount includes all prior amounts up to its order_date. This is incredibly useful for analyzing trends over time without self-joins or subqueries.