【问题标题】:Is there a way to join two tables and then group by some attribute有没有办法连接两个表,然后按某些属性分组
【发布时间】:2019-09-09 17:02:02
【问题描述】:

您好,我有两张表 Emp_774884 和 Dept_774884。

Emp_774884 包含

emp_id  ename  sal  deptid 

Dept_774884 包含

deptid dept_name no_of_emp city

我已尝试以下查询来查找每个部门中薪水最高的员工。

select emp_774884.ename,Max(emp_774884.sal) as salary, dept_774884.DEPT_NAME
from emp_774884 join
      dept_774884
      on dept_774884.deptid = emp_774884.deptid
group by dept_774884.DEPT_NAME ;

但我得到以下结果

ORA-00979: 不是 GROUP BY 表达式 00979. 00000 - “不是 GROUP BY 表达式” *原因:
*行动:

我希望以下列按部门名称分组

姓名工资部门名称

【问题讨论】:

  • 没有右括号吗?请删除后缀编号,Dept_774884 可能是 Dept 或 Department,该编号只会使其更难阅读。

标签: sql oracle


【解决方案1】:

错误似乎很明显——select 中有未聚合的列,而group by 中没有。仅添加列会使错误消失,但不会做您想要的。

Oracle 有一个非常棒的扩展名为 keep,它可以满足您的需求:

select d.DEPT_NAME, max(e.sal) as max_salary,
       max(e.ename) keep (dense_rank first order by e.sal desc) as ename_at_max
from emp_774884 e join
     dept_774884 d
     on d.deptid = e.deptid
group by d.DEPT_NAME ;

请注意,当有联系时,这只会返回一个员工姓名。在这种情况下不清楚你想要什么。

【讨论】:

  • 我想按部门名称划分表格,然后打印每个部门工资最高的名称
  • 以上查询完成了我想要的部分。但是只有一件事是错误的,即emp_774884 不包含dept_name,最后一行应该是d.dept_name。谢谢。你能解释一下它到底在做什么吗?
【解决方案2】:

查询所需内容

select e.ename,d.DEPT_NAME, Max(e.sal) as salary, d.DEPT_NAME
from emp_774884 e join dept_774884 d on ( e.deptid = d.deptid)
 join (select dept_774884.DEPT_NAME, Max(emp_774884.sal) as salary, dept_774884.DEPT_NAME
from emp_774884  e1 join
      dept_774884 d1
      on d1.deptid = e1.deptid
group by dept_774884.deptid) t on (e.deptid = t.deptid)

现在进入正题。为什么你会得到

ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression" *Cause:
*Action:

因此,当您对某些列使用按例外分组时,并且在选择时使用不同的列时,就会出现此异常。

换句话说

您只能选择您在分组依据中提到的那些列。

因此,在您的情况下,您使用 deptid 作为按列分组,但您也选择了其他列。

【讨论】:

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