在mysql中使用average with group by

时间:2017-10-07 16:57:16

标签: mysql sql select

我有三张桌子

EMPLOYEE table with ID and NAME
COMPANY table with ID and NAME
and 
SALARY table with EMPLOYEE_ID, COMPANY_ID and SALARY

我想打印平均工资大于或等于40000的每家公司的名称

我的查询是

Select distinct COMPANY.NAME from COMPANY,SALARY,EMPLOYEE WHERE SALARY.COMPANY_ID=COMPANY.ID and (select avg(SALARY) from SALARY,EMPLOYEE WHERE SALARY.EMPLOYEE_ID=EMPLOYEE.ID) >=40000;

3 个答案:

答案 0 :(得分:4)

您可以按公司名称进行分组,并在having子句中包含条件:

SELECT   c.name
FROM     company c
JOIN     salary s ON c.id = s.company_id
GROUP BY c.name
HAVING   AVG(salary) >= 40000

答案 1 :(得分:1)

SELECT DISTINCT COMPANY.NAME 
FROM COMPANY 
INNER JOIN SALARY ON COMPANY.ID = SALARY.COMPANY_ID 
INNER JOIN EMPLOYEE ON EMPLOYEE.ID = SALARY.EMPLOYEE_ID 
GROUP BY COMPANY.NAME HAVING AVG(SAL)>=40000

答案 2 :(得分:0)

选择T1.NAME 来自T1公司的T1内联(选择COMPANY_ID,AVG(SALARY)AS的平均工资,来自SALARY GROUP BY COMPANY_ID的工资)作为T2 开启T1.ID = T2.COMPANY_ID T2.avgSalary> = 40000;