aggregate tables with AVG

UX Backpacker :

I am new to SQL.

I checked "another solutionSQL JOIN two tables with AVG" posted in StackOverflow. And I don't get the meaning with this line in that article:AVG(score.score * 1.0) Besides, the alternative solution below doesn't work at all:

SELECT songs.id, songs.song, songs.artist, 
    (SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore)
FROM songs 

Here are my tables:

[employees]
Dep ID | SALARY
1      |  500
2      |  200
1      |  300
2      | 1000
2      |  400
3      |  200
3      |  300
[departments]
Dept ID Dep| Dept Name
1          | Volcano
2          | ShootingStar
3          | Tsunami

In the end, I want to create a list looks like:

Dept Name   | Average Salary
Volcano     | $$$
ShootingStar| $$
Tsunami     | $$$$

I tried various ways and hunting hints in stackoverflow for sub queries/inner join features but still can't get it.

Based on the solution in the previous link SQL JOIN two tables with AVG, this code works:

-- mapping DEPT ID with NAME + average salary by DEPT --
select EMPLOYEES.DEP_ID, DEPARTMENTS.DEP_NAME, AVG(EMPLOYEES.SALARY) as AVG_S
from EMPLOYEES 
    LEFT JOIN DEPARTMENTS
    ON EMPLOYEES.DEP_ID = DEPARTMENTS.DEPT_ID_DEP
group by DEP_ID, DEP_NAME;

However, I want to understand the reason WHY my original one doesn't work?

select E.DEP_ID, D.DEP_NAME,  (select AVG(SALARY) from EMPLOYEES group by DEP_ID) as AVG_S
from EMPLOYEES E, DEPARTMENTS D
where E.DEP_ID = D.DEPT_ID_DEP
group by DEP_ID, DEP_NAME;

Please help!

Thank you very much.

GMB :

The query you wanted to write:

select 
    e.dep_id, 
    d.dep_name,  
    (select avg(salary) from employees e where e.dep_id = d.dept_id_dep) as avg_s
from departments d;

The logic of the query is to select from departments only, then use a correlated subquery to compute the average salaries of employees of the department. This avois aggregating in the outer query.

Your query fails in the following regards:

  • table employees is in the from clause of the outer query

  • the outer query does group by

  • the subquery is not corelated on the department

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394841&siteId=1