I have two tables department and employee and this PL/SQL statement that displays company average salary.
DECLARE
v_cavg NUMBER;
BEGIN
SELECT avg(salary) into v_cavg FROM employee;
DBMS_Output.Put_Line('Company Average Salary: ' || RTRIM(TO_CHAR(v_cavg,'$999G999G999D99')));
DBMS_Output.Put_Line('----------------------------------------');
END;
What I am trying to do now is implement a cursor and join together the employee and department tables to get all department names that have a department average salary less than that of the company average salary. I am brand new to cursors and I know I have to have an if statement somewhere along these lines
if v_davg < v_cavg THEN
DBMS_OUTPUT_.PUT_LINE ('Department Name: ' || RPAD(v_dname);
DBMS_Output.Put_Line('Department Average Salary: ' || RTRIM(TO_CHAR(v_davg,'$999G999G999D99')));
DBMS_Output.Put_Line('----------------------------------------');
else
DBMS_Output.Put_Line(' '); /// Nothing here.
END IF;
END;
I am just not sure how to add in a cursor any help would be great!
You actually don't need a cursor, or an IF statement:
SELECT d.name, avg(e.salary)
FROM department d, employee e
GROUP BY d.name
HAVING avg(e.salary) > v_cavg;
If the formatting of the output is important, you could use a cursor to loop through these results like so:
DECLARE
CURSOR c IS
SELECT...(as above);
BEGIN
FOR r IN c LOOP
dbms_output.put_line('Department Name: '||r.name);
-- Etc, etc.
END LOOP;
END;
A simple statement would help.
10:17:37 HR@sandbox> ed
Wrote file S:\tools\buffer.sql
1 select d.department_name
2 from departments d
3 ,employees e
4 where d.department_id = e.department_id
5 group by d.department_name
6* having avg(salary) < (select avg(salary) from employees)
10:18:23 HR@sandbox> /
DEPARTMENT_NAME
------------------------------
Administration
Purchasing
IT
Shipping
Elapsed: 00:00:00.09
You can also wrap it in a cursor like this:
10:18:23 HR@sandbox> ed
Wrote file S:\tools\buffer.sql
1 begin
2 for i in (
3 select d.department_name
4 from departments d
5 ,employees e
6 where d.department_id = e.department_id
7 group by d.department_name
8 having avg(salary) < (select avg(salary) from employees)
9 ) loop
10 dbms_output.put_line(i.department_name);
11 end loop;
12* end;
10:20:29 13 /
Administration
Purchasing
IT
Shipping
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.07
Notice the IT department traditionally being one of those with the lowest salary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.