Bird
0
0

You want to calculate the cumulative sum of sales per region ordered by date, and reuse this window in multiple queries. Which is the best way to define and use a named window for this purpose?

hard📝 Application Q15 of 15
PostgreSQL - Window Functions in PostgreSQL
You want to calculate the cumulative sum of sales per region ordered by date, and reuse this window in multiple queries. Which is the best way to define and use a named window for this purpose?
ADefine <code>WINDOW sales_win AS (PARTITION BY region ORDER BY date ROWS UNBOUNDED PRECEDING)</code> and use <code>SUM(sales) OVER sales_win</code>
BUse <code>SUM(sales) OVER (PARTITION BY region ORDER BY date)</code> without WINDOW clause
CDefine <code>WINDOW sales_win AS (ORDER BY date PARTITION BY region)</code> and use <code>SUM(sales) OVER sales_win</code>
DDefine <code>WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)</code> and use <code>SUM(sales) OVER sales_win</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand cumulative sum window frame

    Cumulative sum requires a frame from the start to current row, so use RANGE or ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  2. Step 2: Check window definition correctness

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win correctly defines WINDOW with PARTITION BY region, ORDER BY date, and RANGE frame for cumulative sum.
  3. Step 3: Compare with other options

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date ROWS UNBOUNDED PRECEDING) and use SUM(sales) OVER sales_win uses ROWS UNBOUNDED PRECEDING which sums the entire partition, not cumulatively. Define WINDOW sales_win AS (ORDER BY date PARTITION BY region) and use SUM(sales) OVER sales_win has wrong order of clauses. Use SUM(sales) OVER (PARTITION BY region ORDER BY date) without WINDOW clause does not reuse named window.
  4. Final Answer:

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win -> Option D
  5. Quick Check:

    Named window with correct frame = Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win [OK]
Quick Trick: Use RANGE UNBOUNDED PRECEDING for cumulative sums [OK]
Common Mistakes:
  • Omitting frame clause for cumulative sum
  • Incorrect order of PARTITION BY and ORDER BY
  • Not using named window for reuse

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes