SQL
Calculate Running Total Without Window Functions
Compute a cumulative sum or running total for a set of records in a SQL table using a self-join, offering an alternative to modern window functions for compatibility.
SELECT
t1.SaleDate,
t1.Amount,
SUM(t2.Amount) AS RunningTotal
FROM Sales t1
INNER JOIN Sales t2 ON t1.SaleDate >= t2.SaleDate
GROUP BY t1.SaleDate, t1.Amount
ORDER BY t1.SaleDate;
How it works: This SQL query calculates a running total (cumulative sum) for sales amounts over time without relying on window functions (like SUM() OVER ()), which might not be available or desired in all SQL environments. It achieves this by performing a self-join where the join condition sums all previous and current sales amounts based on the SaleDate, then groups and orders the results to show the cumulative sum for each record.