如何在FUNCTION中使用GROUP功能(MAX)?

时间:2018-12-18 06:41:43

标签: sql database oracle function plsql

CREATE TABLE cursor_table(
emp_id NUMBER(10) PRIMARY KEY,
emp_name VARCHAR2(30),
emp_salary NUMBER(5)
);

INSERT INTO cursor_table VALUES(101,'addeesh',25000);
INSERT INTO cursor_table VALUES(102,'arunkumar',28000);
INSERT INTO cursor_table VALUES(103,'ashokkumar',35000);
INSERT INTO cursor_table VALUES(104,'durairaj',22000);


CREATE OR REPLACE FUNCTION high_payed_emp
RETURN NUMBER 
IS
    high_payed_emp_id NUMBER(10):=0;
    DECLARE max_emp_salary = MAX(emp_salary);
BEGIN
    SELECT emp_id INTO high_payed_emp_id
    FROM cursor_table
    WHERE emp_salary = max_emp_salary;

    RETURN high_payed_emp_id;
END;

我需要创建一个可以找到薪酬最高的员工的函数。

错误消息:在预期以下情况之一时遇到符号“ DECLARE”:begin函数pragma过程子类型类型当前游标已删除

3 个答案:

答案 0 :(得分:1)

请检查下面的代码,您同时遇到语法和逻辑错误。

CREATE OR REPLACE FUNCTION high_payed_emp
RETURN NUMBER 
IS
    high_payed_emp_id NUMBER(10):=0;
BEGIN
  select emp_id 
    into high_payed_emp_id  
  from (
    select emp_id 
    from cursor_Table
    order by emp_salary desc
  )
  where rownum = 1;

  RETURN high_payed_emp_id;
END;

答案 1 :(得分:1)

您需要一条SQL语句才能使用MAX函数。

CREATE OR REPLACE FUNCTION high_payed_emp
RETURN NUMBER 
IS
    high_payed_emp_id NUMBER(10):=0;
     max_emp_salary NUMBER :=0;
BEGIN
    SELECT MAX(emp_salary) 
      INTO max_emp_salary 
      FROM cursor_table;

    SELECT emp_id INTO high_payed_emp_id
    FROM cursor_table
    WHERE emp_salary = max_emp_salary;

    RETURN high_payed_emp_id;
END;

答案 2 :(得分:0)

只需使用子查询比较最高薪水,您的代码应如下所示:

CREATE OR REPLACE FUNCTION high_payed_emp
RETURN NUMBER 
IS
    high_payed_emp_id NUMBER(10);
BEGIN
    SELECT emp_id INTO high_payed_emp_id
    FROM cursor_table
    WHERE emp_salary = (Select max(emp_salary) from cursor_table);
    RETURN high_payed_emp_id;
END;

执行:

Select high_payed_emp from dual;

输出:

HIGH_PAYED_EMP
--------------
           103