SQL : 我如何使用 PL/SQL 但在单个 select 中获取部门名称和部门(Oracle 服务器)的平均工资

SQL : How do i i get a department name and avg salary of departments (Oracle server) using PL/SQL but in a single select

所以基本上我有一个任务。在作业中,我必须打印出部门名称及其平均工资。现在的问题是,我必须使用 PL/SQL,而且我必须使用一个 select。所以本质上是一个子查询。但我一直在思考我应该怎么做,如果有人能帮助我,那就太棒了!

这是代码:

DECLARE
    v_dep_name varchar2 (30);
    v_salay number (11,2);
BEGIN
    SELECT department_name,AVG(salary)
    INTO v_dep_name,v_salay
    FROM  departments NATURAL JOIN employees 
    WHERE department_id=(
        SELECT department_id
        FROM departments
        WHERE department_id=50)
    GROUP BY salary;
    DBMS_OUTPUT.PUT_LINE ('The average salary of the department '||v_dep_name || ' is : ' || v_salay);
    END;
/

根据您的代码,您不需要子查询。正确的代码应该看起来很像 -

DECLARE
    v_dep_name varchar2 (30);
    v_salay number (11,2);
BEGIN
    SELECT department_name,AVG(salary)
      INTO v_dep_name,v_salay
      FROM departments 
   NATURAL JOIN employees 
     WHERE department_id=50
     GROUP BY department_name;       -- This should be department_name instead of salary.

    DBMS_OUTPUT.PUT_LINE ('The average salary of the department '||v_dep_name || ' is : ' || v_salay);
END;
/