PostgreSQL - Window Functions in PostgreSQLWhich window function would you use to calculate a moving average of sales over the last 3 days in PostgreSQL?ACOUNT(sales) OVER (PARTITION BY date)BRANK() OVER (ORDER BY sales)CSUM(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)DMAX(sales) OVER (PARTITION BY date)Check Answer
Step-by-Step SolutionSolution:Step 1: Identify moving average calculationMoving average sums values over a sliding window of rows, here last 3 days means current row plus 2 preceding rows.Step 2: Match window frame clauseROWS BETWEEN 2 PRECEDING AND CURRENT ROW defines a 3-row window for the sum.Final Answer:SUM(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) -> Option CQuick Check:Moving average uses SUM() with ROWS frame [OK]Quick Trick: Use ROWS BETWEEN for moving window sums [OK]Common Mistakes:Using PARTITION BY instead of ORDER BY for moving windowsUsing COUNT() which counts rows, not sums valuesConfusing RANK() with aggregation
Master "Window Functions in PostgreSQL" in PostgreSQL9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More PostgreSQL Quizzes Common Table Expressions - Recursive CTE for hierarchical data - Quiz 8hard Common Table Expressions - Recursive CTE for graph traversal - Quiz 15hard Common Table Expressions - CTE materialization behavior - Quiz 12easy Full-Text Search - Ranking with ts_rank - Quiz 6medium JSON and JSONB - Arrow operators (-> and ->>) - Quiz 12easy JSON and JSONB - Why JSON support matters in PostgreSQL - Quiz 1easy Joins in PostgreSQL - LEFT JOIN and RIGHT JOIN - Quiz 14medium Subqueries in PostgreSQL - Subqueries in FROM (derived tables) - Quiz 1easy Subqueries in PostgreSQL - LATERAL subqueries - Quiz 11easy Window Functions in PostgreSQL - LAG and LEAD for row comparison - Quiz 4medium