single
Running Totals and Moving Averages
Свайпніть щоб показати меню
Running totals and moving averages are essential analytical techniques for understanding trends over time in business data. A running total (also known as a cumulative sum) calculates the sum of a metric up to each point in a sequence, such as the total sales up to each day. This helps you see how a value accumulates, revealing growth patterns or seasonality. A moving average smooths out short-term fluctuations by averaging values over a fixed window (like the last 7 days), making it easier to spot underlying trends.
These calculations are widely used in business scenarios:
- A retail manager might use running totals to track cumulative sales during a promotion;
- A SaaS company could use a 7-day moving average of new signups to understand ongoing growth, filtering out daily spikes or dips;
- Finance teams often rely on moving averages for revenue forecasting;
- Marketing analysts use running totals to monitor campaign performance as it unfolds.
Window frame clauses, such as ROWS BETWEEN, define the subset of rows used for window function calculations in SQL. For running totals, the frame is typically specified as ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, meaning the calculation includes all rows from the start of the partition up to the current row.
1234567SELECT sale_date, total_amount, SUM(total_amount) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM sales ORDER BY sale_date;
A common use case for moving averages is when the finance team wants to analyze trends in daily revenue, but without the noise of daily fluctuations. Suppose the finance team requests a report showing the 7-day moving average of daily revenue for the SaaS platform. This helps them understand the underlying revenue trend and make better forecasts.
12345678910SELECT order_date::date AS day, SUM(total) AS daily_revenue, AVG(SUM(total)) OVER ( ORDER BY order_date::date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) AS moving_avg_7d FROM orders GROUP BY order_date::date ORDER BY day;
Проведіть, щоб почати кодувати
Write a query to compute the cumulative number of new users registered each month.
- Group users by the month of their signup date.
- Count the number of new users for each month.
- Calculate a cumulative total of new users up to and including each month.
Рішення
Дякуємо за ваш відгук!
single
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат