查找那些员工的平均工资高于“ Wipro”平均工资的公司

时间:2018-10-19 18:31:28

标签: mysql sql

我尝试了一个sql但没有用

select cname,avg(salary) from Company as co,Works as wo where co.cid=wo.cid and wo.salary > (select avg(salary) from Company as c,Works as w where c.cid=w.cid and c.cname='Wipro');

员工(EID,EName,城市)

作品(EID,CID,薪金)

公司(客户ID,CNAME,城市)

创建表Employee(eid int主键,ename varchar(6),city varchar(6))

创建表Works(eid int,cid int主键,salary int)

创建表Company(cid int,cname varchar(6),city varchar(6))

变更表Works添加外键(eid)引用Employee(eid)

更改表Works添加外键(cid)引用公司(cid)

4 个答案:

答案 0 :(得分:1)

学习使用正确的,明确的,标准 JOIN语法。

也就是说,你很亲密。您只需要一个HAVING子句:

select c.cname, avg(w.salary)
from Company c join
     Works w
     on c.cid = w.cid 
group by c.cname
having avg(w.salary) > (select avg(w2.salary)
                        from Company c2 join
                             Works w2
                             on c2.cid = w2.cid 
                        where c2.cname = 'Wipro'
                       );

注意:

  • 从不FROM子句中使用逗号。
  • 使用GROUP BY时应使用AVG()
  • 总结值的条件应放在HAVING子句中。

答案 1 :(得分:0)

SELECT t1.CName, 
       t2.AvgSalary
FROM Company t1
INNER JOIN (SELECT AVG(Salary) AS AvgSalary, 
            CID
            FROM Works
            GROUP BY CID) t2 ON t1.CID = t2.CID
WHERE t2.AvgSalary > (SELECT AVG(Salary)
                      FROM blog.Works t1a
                      INNER JOIN blog.Company t2a ON t1a.cid = t2a.cid 
                      WHERE t2a.cname = 'Wipro');

答案 2 :(得分:0)

尝试一下:

Select cname
FROM
(select cname,cid,avg(salary) as avg_sal
from works w 
join company c
on w.cid = c.cid
group by w.cid,w.cname
)a,
(
select avg(salary) as avg_wipro
from works w
join company c
on w.cid = c.cid
and ccname='Wipro'
)b
WHERE a.avg_sal > b.avg_wipro

答案 3 :(得分:0)

如果有GROUP BY,则可以在HAVING子句中使用聚合函数,例如SUM。

SELECT 
co.cname AS company_name, 
AVG(wo.salary) AS avg_salary 
FROM Company AS co 
JOIN Works AS wo ON wo.cid = co.cid 
GROUP BY co.cname 
HAVING AVG(wo.salary) > (
       SELECT AVG(salary) 
       FROM Company AS c 
       JOIN Works AS w ON w.cid = c.cid 
       WHERE c.cname = 'Wipro'
      );

您可以尝试here