Bird
0
0

You want to calculate a running average salary per department ordered by hire date. Which query correctly uses AVG() as a window function?

hard📝 Application Q8 of 15
PostgreSQL - Window Functions in PostgreSQL
You want to calculate a running average salary per department ordered by hire date. Which query correctly uses AVG() as a window function?
ASELECT employee_id, department, salary, AVG(salary) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_avg FROM employees;
BSELECT employee_id, department, salary, AVG(salary) OVER (ORDER BY hire_date PARTITION BY department) AS running_avg FROM employees;
CSELECT employee_id, department, salary, AVG(salary) OVER (PARTITION BY department) AS running_avg FROM employees;
DSELECT employee_id, department, salary, AVG(salary) FROM employees PARTITION BY department ORDER BY hire_date;
Step-by-Step Solution
Solution:
  1. Step 1: Understand running average with window frame

    To calculate running average, use AVG() OVER with PARTITION BY department, ORDER BY hire_date, and frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  2. Step 2: Validate syntax

    SELECT employee_id, department, salary, AVG(salary) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_avg FROM employees; correctly uses all required clauses in correct order and frame specification.
  3. Final Answer:

    SELECT employee_id, department, salary, AVG(salary) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_avg FROM employees; -> Option A
  4. Quick Check:

    Running average needs frame clause with ORDER BY [OK]
Quick Trick: Use ROWS BETWEEN for running calculations [OK]
Common Mistakes:
  • Swapping PARTITION BY and ORDER BY order
  • Omitting window frame for running average
  • Using aggregate AVG() without OVER()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes