编写一个 PL/SQL 块,从 Employee 表中显示部门名称和该部门的总工资支出
Posted
技术标签:
【中文标题】编写一个 PL/SQL 块,从 Employee 表中显示部门名称和该部门的总工资支出【英文标题】:Write a PL/SQL block to display the department name and the total salary expenditure of the department from the Employee table 【发布时间】:2020-08-29 14:02:27 【问题描述】:在Employee表中显示部门名称和部门工资支出总额。
要查找部门名称和来自特定部门的人的薪水必须是输出。
THIS IS THE EMPLOYEE TABLE:
EMP_ID EMP_NAME SALARY DEPT
101 Tom 54000 MECH
102 William 43000 CSE
103 John 34560 MECH
104 Smith 56000 CSE
105 Steve 23450 IT
编码:
我试过这个,但我没有得到输出,谁能帮我得到输出。
set serveroutput on;
DECLARE
Dept varchar2(25);
Employee_salary VARCHAR2(25);
SELECT
Employee_salary
FROM
Employee;
WHERE salary=23450;
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Department-wise salary expenditure :’ || Dept salary);
END;
/
以及示例输出:
Department-wise salary expenditure:
IT department, total salary is 48000
CSE department, total salary is 79000
MECH department, total salary is 80000
【问题讨论】:
您发布的代码甚至无法编译。据推测,当您尝试运行它时会收到错误消息。为了将来参考,您应该在问题中包含此类错误。此外,您应该为 Oracle PL/SQL 手册添加书签。它有很多例子向你展示如何编写这样的程序。 Here is the chapter on using SQL in PL/SQL 与***.com/q/63647481/230471 相同的问题。引号字符是'
而不是 ’
。
谢谢您的指导先生。我得到了输出
【参考方案1】:
您需要一个循环(在 PL/SQL 中)来显示所有部门。例如:
SQL> begin
2 dbms_output.put_line('Department-wise salary expenditure:');
3 for cur_r in (select dept, sum(salary) sumsal
4 from employee
5 group by dept
6 order by dept
7 )
8 loop
9 dbms_output.put_line(rpad(cur_r.dept, 4, ' ') ||
10 ' department, total salary is ' || cur_r.sumsal);
11 end loop;
12 end;
13 /
Department-wise salary expenditure:
CSE department, total salary is 99000
IT department, total salary is 23450
MECH department, total salary is 88560
PL/SQL procedure successfully completed.
SQL>
(rpad
在这里只是为了很好地对齐输出)
就您编写的代码而言:它无法编译,错误太多。固定(但仍然没有做你需要的)将是
SQL> DECLARE
2 Dept varchar2(25);
3 Employee_salary VARCHAR2(25);
4 begin
5 SELECT salary
6 into employee_salary
7 FROM Employee
8 WHERE salary=23450;
9
10 DBMS_OUTPUT.PUT_LINE('Department-wise salary expenditure :' || employee_salary);
11 END;
12 /
Department-wise salary expenditure :23450
PL/SQL procedure successfully completed.
SQL>
那么,你做错了什么?
begin
需要放在声明部分之后;你在下面的某个地方
PL/SQL 中的select
需要into
子句
where
子句没用;您正在尝试选择恰好为 23450 的薪水;如果没有,您的查询将返回 no_data_found
错误。如果两个(或更多)员工赚了这么多,你会收到too_many_rows
错误
fancy dbms_output.put_line
中的单引号
您正在显示不存在的变量(并且不能分成两个单独的名称,dept salary
【讨论】:
谢谢您的指导先生。我得到了输出。【参考方案2】:set serveroutput on;
declare
cursor c_depts is select DEPT, sum(SALARY) as sumsal from employee group by DEPT;
v_depts c_depts%rowtype;
begin
open c_depts;
dbms_output.put_line('Department-wise salary expenditure:');
loop
fetch c_depts into v_depts;
exit when c_depts%notfound;
dbms_output.put_line(v_depts.DEPT || ' department, total salary is ' || v_depts.sumsal );
end loop;
close c_depts;
end;
/
【讨论】:
感谢您的回答。您能通过解释上面的代码块的作用来帮助我们理解它吗?【参考方案3】:我不确定您为什么要使用 PL/SQL,除非这是练习的要求。您似乎只想要一个聚合查询:
SELECT dept, SUM(Employee_salary) as total_salary
FROM Employee;
GROUP BY dept;
【讨论】:
以上是关于编写一个 PL/SQL 块,从 Employee 表中显示部门名称和该部门的总工资支出的主要内容,如果未能解决你的问题,请参考以下文章