【问题标题】:sql subqueries and group bysql子查询和分组依据
【发布时间】:2014-03-18 13:30:27
【问题描述】:

我正在为我的 sql 类分配一个我似乎无法弄清楚的任务。这是对所需选择的描述:

显示工资高于所在部门同事平均工资的所有员工,仅适用于至少有 4 名员工的部门。

我已经能够找到部分查询,例如

select ename 
  from emp
 where sal > any (select avg(sal) 
                    from emp 
                  group by 
                         deptno);

获取收入超过平均水平的员工的姓名。

select count(deptno) 
  from emp
group by 
       deptno having count(deptno) > 4;

获取每个部门的员工人数。

但不知何故,将它们联系在一起是行不通的。也许有人可以帮助我阐明这一点。

【问题讨论】:

    标签: sql oracle11g


    【解决方案1】:

    只需将第二个查询放入 AND 子句即可:

    select ename 
      from emp
     where sal > any (select avg(sal) 
                        from emp 
                      group by 
                             deptno)
    and deptno in (select deptno
                   from emp
                   group by 
                   deptno having count(deptno) > 4);
    

    【讨论】:

    • 一个简单的解决方案。谢谢
    【解决方案2】:

    您可以将 Having ClauseGroup By

    结合使用
    select ename 
      from emp
     where sal > any (select avg(sal) 
                        from emp 
                      group by 
                             deptno) 
    having count(*)>4;
    

    【讨论】:

      【解决方案3】:
      select ename 
        from (
              select deptno, count(deptno) 
              from emp
              group by deptno
              having count(deptno) > 4) valid_depts join emp ON emp.deptno=valid_depts.deptno
       where sal > any (select avg(sal) 
                          from emp 
                         group deptno);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多