Bird
0
0

Given the table sales(date, amount) ordered by date, what is the output of this query?

medium📝 query result Q13 of 15
SQL - Window Functions Fundamentals
Given the table sales(date, amount) ordered by date, what is the output of this query?
SELECT date, amount, SUM(amount) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS running_sum FROM sales;

Assuming data:
date | amount
2024-01-01 | 100
2024-01-02 | 200
2024-01-03 | 300
A[{"date": "2024-01-01", "amount": 100, "running_sum": 300}, {"date": "2024-01-02", "amount": 200, "running_sum": 500}, {"date": "2024-01-03", "amount": 300, "running_sum": 600}]
B[{"date": "2024-01-01", "amount": 100, "running_sum": 100}, {"date": "2024-01-02", "amount": 200, "running_sum": 200}, {"date": "2024-01-03", "amount": 300, "running_sum": 300}]
C[{"date": "2024-01-01", "amount": 100, "running_sum": 100}, {"date": "2024-01-02", "amount": 200, "running_sum": 300}, {"date": "2024-01-03", "amount": 300, "running_sum": 500}]
D[{"date": "2024-01-01", "amount": 100, "running_sum": null}, {"date": "2024-01-02", "amount": 200, "running_sum": 300}, {"date": "2024-01-03", "amount": 300, "running_sum": 500}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand frame range

    The frame includes the current row and 1 row before it, so for each row sum amounts of current and previous row.
  2. Step 2: Calculate running sums

    Row 1: only 100 (no previous row), Row 2: 100+200=300, Row 3: 200+300=500.
  3. Final Answer:

    [{"date": "2024-01-01", "amount": 100, "running_sum": 100}, {"date": "2024-01-02", "amount": 200, "running_sum": 300}, {"date": "2024-01-03", "amount": 300, "running_sum": 500}] -> Option C
  4. Quick Check:

    Sum current + 1 preceding = A [OK]
Quick Trick: Sum includes current and 1 previous row amounts [OK]
Common Mistakes:
  • Including 2 rows before instead of 1
  • Ignoring the order of rows
  • Assuming NULL for first row sum

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes