Last answered:

22 May 2024

Posted on:

16 May 2023

0

CTE exercise 1

I am getting a different value by using this query can you please check 

I have used a slightly different approach

First I have created a table emp_no | gender | salary  and used a cross join with avg_sal with  a filter criteria of male employees who have signed a contract above the average salary.

After that I used a left join with employees table to identify male employees with salary below average.



SELECT COUNT(e.emp_no) as num_of_emp_below_avg from employees e
LEFT JOIN (SELECT s.emp_no, e.gender, s.Salary, c.avg_sal
FROM salaries s join employees e on s.emp_no = e.emp_no
CROSS JOIN (SELECT AVG(SALARY) AS avg_sal FROM SALARIES) AS c
WHERE e.gender = "M" AND s.salary > c.avg_sal) AS B on e.emp_no = B.emp_no 
where e.gender = "M";

1 answers ( 0 marked as helpful)
Instructor
Posted on:

22 May 2024

0

Hi Barun!

Thanks for reaching out!


Your structure is correct. However, there are two notes:

1) You have to use JOIN instead of LEFT JOIN.

2) You have to use WHERE e.gender = 'M' AND s.salary < c.avg_sal instead of WHERE e.gender = 'M' AND s.salary > c.avg_sal. The reason is that we are asking for these males which have never signed a contract with a salary value higher than or equal to the all-time company salary average. This means we search for these males with a salary lower than the all-time company average, not greater.
 

Hope this helps.
Best,
Martin

Submit an answer