如何在SQL中使用内部查询的输出

时间:2016-11-13 23:23:29

标签: sql oracle

我在Oracle 11g数据库中有2个表,即EARNEDRATINGEMPLOYEE

EMP_NUM    RTG_CODE     EARNRTG_DATE
------------------------------------
101          CFI         18-Feb-98
101          CFII        15-Dec-05
101          INSTR       8-Nov-93
101          MEL         23-Jun-94
101          SEL         21-Apr-93


EMP_NUM EMP_LNAME   EMP_FNAME
-----------------------------
101     Kolmyoz      George

我想写一个查询,查找所有员工的emp_num,emp_fname,emp_lname及其获得的评分数。

我试过这个

select 
    er.emp_num, e.emp_fname, e.emp_lname, 
    count(er.rtg_code) as "Number of Earned Rating" 
from 
    earnedrating er 
join 
    employee e on er.emp_num=e.emp_num  
group by 
    er.emp_num;

但是收到此错误

  

不是GROUP BY表达式

4 个答案:

答案 0 :(得分:3)

您必须分组 不在聚合函数中的所有列:

select er.emp_num,
       e.emp_fname,
       e.emp_lname,
       count(er.rtg_code) "Number of Earned Rating" 
from earnedrating er,employee e 
where er.emp_num = e.emp_num  
group by er.emp_num , e.emp_fname, e.emp_lname;

答案 1 :(得分:2)

你可能需要

中的所有列
        select 
              er.emp_num
            , e.emp_fname
            , e.emp_lname
            , count(er.rtg_code)   "Number of Earned Rating" 
        from earnedrating er 
        join employee e on er.emp_num = e.emp_num  
        group by er.emp_num , e.emp_fname, e.emp_lname;

答案 2 :(得分:2)

使用GROUP BY时,返回的所有字段必须位于group by子句中,或者在聚合函数中使用。在您的示例中,您可以将第一个名称和姓氏添加到group by:

select er.emp_num
    , e.emp_fname
    , e.emp_lname
    , count(er.rtg_code) as "Number of Earned Rating" 
from earnedrating er 
    inner join employee e on er.emp_num=e.emp_num  
group by er.emp_num, e.emp_fname, e.emp_lname;

答案 3 :(得分:0)

SELECT s.emp_num, 
       e.emp_fname,
       e.emp_lname,
       s.rtg_code_count as "Number of Earned Rating" 
FROM (Select er.emp_num, 
             COUNT(er.rtg_code) as rtg_code_count 
      FROM earndrating er group by er.emp_num) as s,
     employee e 
WHERE s.emp_num=e.emp_num;