加入SQL查询会出现ORA-00937错误

时间:2017-06-22 18:14:41

标签: sql oracle group-by

      DECLARE

    v_department_name VARCHAR(50);
    v_department_manager VARCHAR(50);
    v_totalsalary NUMBER(5);

     BEGIN

  SELECT departments.department_name, concat(employees.first_name, employees.last_name), sum(employees.salary) 
  INTO v_department_name, v_department_manager, v_totalsalary 
  FROM employees LEFT JOIN departments ON employees.department_id =departments.department_id  WHERE  departments.department_id = 100;

   DBMS_OUTPUT.PUT_LINE ('Department Name is: ' || v_department_name || 'And    Department Manager is: ' || v_department_manager || 'Total Amount of Salary is: ' || v_totalsalary );

   END;

尝试显示department_name,部门经理(first_name,last_name)以及所赚取的工资总额时 部门ID为100的员工,我明白了:

  

ORA-00937:不是单组组功能

导致该错误的原因是什么?

表员工(employee_id,first_name,last_name,department_id,manager_id,薪水)

表部门(department_id,department_name,manager_id,location_id)

2 个答案:

答案 0 :(得分:1)

ORA-00937:只是意味着您需要GROUP BY子句,并在该子句中重复不使用聚合函数(如SUM / MIN / MAX等)的select子句的每一列。 / p>

    SELECT
       departments.department_name
     , LISTAGG (employees.first_name || employees.last_name, '; ' )
           WITHIN GROUP (ORDER BY employees.last_name,employees.last_name) employee_names
     , SUM(employees.salary)
    FROM employees
    INNER JOIN departments ON employees.department_id = departments.department_id
    WHERE departments.department_id = 100
    GROUP BY
       departments.department_name
    ; 

注意我正在使用LISTAGG(),但您不必使用它。如果您的3列需要是Department,Department Manager和(薪水总和),那么您需要从Manager的department表中选择正确的字段,然后在select和group by子句中包含该列。

答案 1 :(得分:1)

WITH temp AS (
    SELECT d.department_name, concat(e.first_name, e.last_name) AS emp_name, 
        sum(e.salary) AS salary_sum
    FROM employees e LEFT JOIN departments d ON e.department_id =d.department_id  
    WHERE d.department_id = 100
    GROUP BY d.department_name, concat(e.first_name, e.last_name)  )
SELECT t.department_name, t.emp_name, t.salary_sum
INTO v_department_name, v_department_manager, v_totalsalary 
FROM temp  

此查询使用公用表表达式将数据分组在一起,以使所有内容更加一致。您收到错误是因为您错过了原始查询中的GROUP BY d.department_name, concat(e.first_name, e.last_name)行。 SUM()是一个聚合函数,只能与GROUP BY一起使用。