ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

SQL: Calculate Running Total of Sales by Date

SQL

Goal -- WPM

Ready
Exercise Algorithm Area
1SELECT
2sale_date,
3daily_sales,
4SUM(daily_sales) OVER (ORDER BY sale_date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total_sales
5FROM
6DailySales
7ORDER BY
8sale_date ASC;
Algorithm description viewbox

SQL: Calculate Running Total of Sales by Date

Algorithm description:

This SQL query calculates a running total of sales for each day. It uses the `SUM()` window function with an `ORDER BY` clause to accumulate sales from the beginning up to the current date. This is valuable for trend analysis, performance tracking over time, and forecasting.

Algorithm explanation:

The query selects the `sale_date`, `daily_sales`, and calculates the `running_total_sales`. The `SUM(daily_sales)` is a window function that aggregates sales. The `OVER (ORDER BY sale_date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)` clause specifies how the sum should be computed: it orders the rows by `sale_date` in ascending order and sums all values from the first row (`UNBOUNDED PRECEDING`) up to the current row (`CURRENT ROW`). The outer `ORDER BY sale_date ASC` ensures the final output is chronologically sorted. The time complexity is typically O(N log N) due to the sorting within the window function, where N is the number of rows in `DailySales`. Space complexity is O(N) for storing intermediate results and the final output.

Pseudocode:

SELECT
    sale_date,
    daily_sales,
    SUM(daily_sales) OVER (ORDER BY sale_date ASC) AS running_total_sales
FROM
    DailySales
ORDER BY
    sale_date ASC