I want to understand if my query is correct and if it's efficient than 1st query
Write a query to display the employee id, first name and last name, SalaryDrawn, AvgCompare (salary - the average salary of all employees) and the SalaryStatus column with a title HIGH and LOW respectively for those employees whose salary is more than and less than the average salary of all employees.
SAMPLE employee table:
EMPLOYEE_ID | FIRST_NAME | LAST_NAME | SALARY | MANAGER_ID | DEPARTMENT_ID|
1st Query
SELECT employee_id, first_name, last_name, salary AS SalaryDrawn,
ROUND((salary -(SELECT AVG(salary) FROM employees)),2) AS AvgCompare,
CASE WHEN salary >=
(SELECT AVG(salary)
FROM employees) THEN 'HIGH'
ELSE 'LOW'
END AS SalaryStatus
FROM employees;
My Answer using a CTE and windows function:
WITH cte AS
(SELECT employee_id, first_name, last_name, salary,
ROUND(AVG(Salary) OVER (),2) AS avgSal
FROM employees)
Select employee_id, first_name, last_name, salary, ROUND((e.salary - avgSal ,2) AS AvgCompare,
CASE WHEN salary >= avgSal THEN 'HIGH'
ELSE 'LOW'
END AS SalaryStatus
FROM cte