How can i write a query in PL/SQL to find 3 maximum balance from Account table using cursor?

我只是一个虾纸丫 提交于 2020-01-25 21:37:51

问题


DECLARE
     CUSTID NUMBER; ANO NUMBER; BALANC NUMBER; TYP ACCOUNT.TYPE%TYPE; STATU ACCOUNT.STATUS%TYPE;
     CURSOR S IS SELECT *  FROM ACCOUNT WHERE STATUS = 'active';
BEGIN
    OPEN S;
     FOR A IN 1..3 LOOP
        FETCH S 
        DBMS_OUTPUT.PUT_LINE('CUST ID : '||CUSTID||'   NO:'||ANO || '  TYPE :' || TYP || '   STATUS :' || STATU); 
     END LOOP;
CLOSE S;
END;

i'm trying to find 3 maximum balance on ACCOUNT table but it doesn't work !


回答1:


You don't need PL/SQL or a cursor for this:

SELECT * 
FROM 
  SELECT a.*,
         dense_rank() over (order by balance desc) as rnk
  FROM account 
  WHERE status = 'active' 
) t
WHERE rnk <= 3;



回答2:


Like @a_horse_with_no_name wrote, you don't need pl/sql to do that. In fact, if you have oracle 12c, you even have order by offset. If yo REALLY want to do that in pl/sql you need to change that fetch, and add the INTO clause, for that, you'll need a rowtype variable:

declare
  CURSOR S IS SELECT *  FROM ACCOUNT WHERE STATUS = 'active';
  v_row account%rowtype;
begin
  OPEN S;
     FOR A IN 1..3 LOOP
        FETCH S into v_row;
        DBMS_OUTPUT.PUT_LINE('CUST ID : '||v_row.CUSTID||'   NO:'||v_row.ANO || '  TYPE :' || v_row.TYP || '   STATUS :' || v_row.STATU); 
     END LOOP;
CLOSE S;
end;

ps: there are a lot better ways to do that. I'm just mending your code.




回答3:


There is simple query for this:

select * from(select * from account order by balance desc)where rownum<=3

Embed it in your query

DECLARE
 CUSTID NUMBER; ANO NUMBER; BALANC NUMBER; TYP ACCOUNT.TYPE%TYPE; STATU ACCOUNT.STATUS%TYPE;
 CURSOR S IS (select * from(select * from account order by balance desc)where rownum<=3)

 BEGIN
OPEN S;
 FOR A IN 1..3 LOOP
    FETCH S 
    DBMS_OUTPUT.PUT_LINE('CUST ID : '||CUSTID||'   NO:'||ANO || '  TYPE :' || TYP || '   STATUS :' || STATU); 
 END LOOP;
CLOSE S;
END;


来源:https://stackoverflow.com/questions/43678833/how-can-i-write-a-query-in-pl-sql-to-find-3-maximum-balance-from-account-table-u

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!