Skip to content
Quantoros

Ordered by hiredate: return name, salary, and the average of this salary and the two hired just before, rounded to 0…

SQLLevel: IntermediateWindow functions

Ordered by hire_date: return name, salary, and the average of this salary and the two hired just before, rounded to 0 decimals (mov_avg_3).

Table definitions (from the source exercise):

CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: AVG(salary) OVER (ORDER BY hire_date, emp_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).

SELECT name, salary,
       ROUND(AVG(salary) OVER (ORDER BY hire_date, emp_id
             ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 0) AS mov_avg_3
FROM employees;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions