How to find the second largest in a pl/sql table

Hello friends,

I want to find the first and second maximum items in a pl/sql table.

Here's the code...

DECLARE
Max_earnings_type TYPE TABLE IS NUMBER;
max_earnings_tab max_earnings_type: = max_earnings_type();
number of v_count: = 0;
number of v_max_earnings;


Can someone give me how to find the maximum first max and second in the type of the given table.

appreciate your help.

Thank you/kumar

Published by: kumar73 on October 21, 2010 09:42

kumar73 wrote:

When I tried to implement your logic in my application, I get the following error...

PL/SQL: digital or value error: NULL index key value table

What happens if the PL/SQL table has NULL values. Question is how you want to handle NULL values. You want to ignore nulls as GROUP BY do? If you want to consider NULL values, you can say if you want to order the NULLS FIRST or NULLS LAST. I guess that logical GROUP BY:

DECLARE
    TYPE max_earnings_type IS TABLE OF NUMBER;
    TYPE max_earnings_sorted_type IS TABLE OF NUMBER
      INDEX BY BINARY_INTEGER;
    max_earnings_tab        max_earnings_type;
    max_earnings_tab_sorted max_earnings_sorted_type;
BEGIN
    SELECT  sal + comm
      BULK COLLECT
      INTO  max_earnings_tab
      FROM  emp;
    FOR v_i in 1..max_earnings_tab.count LOOP
      IF max_earnings_tab(v_i) IS NOT NULL
        THEN
          max_earnings_tab_sorted(max_earnings_tab(v_i)) := 1;
      END IF;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('MAX value in PL/SQL table is ' || nvl(to_char(max_earnings_tab_sorted.last),'NULL'));
    DBMS_OUTPUT.PUT_LINE('Second MAX value in PL/SQL table is ' || nvl(to_char(max_earnings_tab_sorted.prior(max_earnings_tab_sorted.last)),'NULL'));
END;
/
MAX value in PL/SQL table is 2650
Second MAX value in PL/SQL table is 1900

PL/SQL procedure successfully completed.

SQL> SELECT  sal + comm
  2    FROM  emp;

  SAL+COMM
----------

      1900
      1750

      2650

      1500

  SAL+COMM
----------

14 rows selected.

SQL>

SY.

Tags: Database

Similar Questions

  • How to find the name of a column in a table

    Hi all

    I have a Table that contains approximately 100 columns.


    I need to find the column name, to find in specific columns containing data like 'abc '.

    Ex: I have a table like temp_table_name
    the columns are col1, col2, col3, col4, col5, col6, col7, col8,.... col99
    I'm looking for with data specific like 'abc '.

    Need to find the name of the table column that contains data of 'abc '.

    Please suggest me. How to find in a single query... :-)

    Actually I'm looking through a column of the table as below
    Select count (*) in the temp_table_name where col1 = 'abc '.

    FOR I IN 1.20 LOOP
    ln_num_of_rows: = 0;
    lv_column_name_search: = "col" | I have;

    lv_sql: = ' select count (*) in the temp_table_name where ' | lv_column_name_search | "= abc";

    EXECUTE IMMEDIATE lv_sql INTO ln_num_of_rows;

    IF ln_num_of_rows > 0
    -column found in lv_column_name_search
    EXIT;
    END IF;
    END LOOP;

    But I'm gettig performance problem.

    How can I do this in any other alternative way? could you suggest any way possible as soon as POSSIBLE.

    It's probably never going to be effective - realistic, you have to scan completes the picture.

    You could probably improve a little things by doing something like

    SELECT DISTINCT column_name
      FROM (
        SELECT (CASE WHEN col1 = 'abc' THEN 'col1'
                    WHEN col2 = 'abc' THEN 'col2'
                    WHEN col3 = 'abc' THEN 'col3'
                    ...
                    WHEN col20 = 'abc' THEN 'col20'
                    ELSE NULL
                    END) column_name
          FROM table_name
        WHERE col1 = 'abc'
            OR col2 = 'abc'
            ...
            OR col20 = 'abc'
      )
    

    but it's never going to be incredibly fast.

    Justin

  • How to create the constructor function for a pl/sql table?

    I created a PL/SQL type as table below:

    create or replace type typ_tbl_des_text is table of the typ_tof_des_text

    OK so far, but I would like to have a constructor function which would be subject to validations and raise_application_error when a validation condition is not met.

    How to do this?

    The typ_tof_des_text that I created with a constructor function, so that the record-level validation are performed in the constructor. And I think the postings between several records shall be made in a constructor for typ_tbl_des_tex, but cannot figure out how to create such a constructor.

    BEDE wrote:

    So, if I have understood correctly, to a plsql table type, I can't have a member procedure. Or can I? I mean, just as for a type of failure I can have one or more constructors and possibly several procedures of Member.

    For the standard tables in PL/SQL, you will need to create your own API (using procedures and functions) to handle beyond the basics provided by the language. No constructors and methods as it is no o - o.

    After thinking a little deeper, I reformulate what I said earlier and actually wants to have a member procedure called add_item, who would be first to check if an item with a key value exists and, if so, it would be up-to-date and so not only extend the plsql table.

    Two options.

    As we already mentioned, an associative array can be considered - note however that this structure of table has name-value pairs.

    Another method is to use a TWG (global temporary table). You define the structure of the once initial table. When a session uses the structure of the table, private copying is instantiated for this session. When the session ends, this copy is destroyed. The table is a temporary structure for this session only.

    It can include indexes and so on – which means you can use the constraints of primary keys, unique indexes, secondary indexes and so on.

    TWG scales are much better than collections or arrays that require a PGA (expensive private server) memory. In addition, SQL can be used natively against a GTT - unlike the arrays and collections.

  • How to find the largest

    DECLARE

    Num_tab_ty TYPE TABLE IS NUMBER;

    num_tab num_tab_ty: = num_tab_ty (6,4,8,7);

    BEGIN

    -How to find the largest and the lowest number in a collection

    END;

    DECLARE

    Num_tab_ty TYPE TABLE IS NUMBER;

    num_tab num_tab_ty: = num_tab_ty (6,4,8,7);

    number of l_greatest_value;

    BEGIN

    Select max (column_value)

    in l_greatest_value

    table (num_tab);

    END;

    /

    HTH

  • How to find the first Sunday and the second Saturday of each month

    Hi all

    How to find the first Sunday and the second Saturday of each month

    Thank you

    Oracle Database 11 g Enterprise Edition Release 11.1.0.7.0 - 64 bit Production

    994122 wrote:

    Hello

    I need to pass the months parameter how to do this? like Jan, Feb etc... (one of those)

    Do you have a procedure?

    Should you output only for the months you passed in the parameter?

    The easiest way is to set the parameter as date. When you go such as p_date as DATE ' 2014-10-01', then you can

    PROCEDURE two_dates)

    p_date IN DATE

    p_first_sunday DATE

    p_second_saturday DATE

    )

    IS

    BEGIN

    p_first_sunday: = NEXT_DAY (TRUNC (p_date, 'MM') - 1, TO_CHAR (DATE ' 2014-10-12', 'DAY'));

    p_second_saturday: = NEXT_DAY (TRUNC (p_date, 'MM') - 1, TO_CHAR (DATE ' 2014-10-11', 'DAY')) + 7;

    END two_dates;

    Or you describe what you need.

  • Equium M50 - cannot find the second memory location

    I just bought 2 X 1 GB memory sticks to upgrade my laptop. I skipped one at the back of the machine and it works fine but I can't find the second memory location. I have to open the machine? And if so, how.

    Any help appreciated...

    Hello

    Second memory slot is not so easy to find because you have to remove the keyboard and the top cover. Please contact your dealer and ask him for help. Please do not try to do anything only because you can cancel the warranty.

  • How to find the number of data items in a file written with the ArryToFile function?

    I wrote a table of number in 2 groups of columns in a file using LabWindows/CVI ArrayToFile... Now, if I want to read the file with the FileToArray function so how do I know the number of items in the file. during the time of writing, I know how many elements array to write. But assume that I want the file to be read at a later time, then how to find the number of items in the file, so that I can read the exact number and present it. Thank you all

    Hello

    I start with the second question:

    bytes_read = ReadLine (file_handle, line_buffer, maximum_bytes);

    the second argument is the buffer to store the characters read, so it's an array of characters; It must be large enough to hold maximum_bytes the value NULL, if char [maximum_butes + 1]

    So, obviously the number of lines in your text tiles can be determined in a loop:

    Open the file

    lines = 0;

    While (ReadLine () > 0)

    {

    lines ++;

    }

    Close the file

  • How to get the second clue high table max and min

    Hello

    I need help to find the second clue to the data table, how can I do?

    Secure with the extract of vi.

    Thank you and best regards,

    Simon

    You forgot to make the comparison to see where the 2nd most high index has declined compared to the highest.

    You only add 1 if the 2nd above comes after the highest.  You added 1 regardless of the position.

  • How to find the url of adf application that has been deployed to the glassfish Server? I try but? It is the image of the page.

    Mr President

    This is the page of the glassfish Server

    gfurl.png

    How to find the url of adf application that has been deployed to the glassfish Server? I try but? It is the image of the page.

    webapplink.png

    In the jdev web module are

    [11: 09:38] wrote the Web for F:\backup of AshCMS\AshCMS\ViewController\deploy\AshCMS_ViewController_webapp.war application Module

    [11: 10:33] wrote the Module Enterprise Application to F:\backup of AshCMS\AshCMS\deploy\AshCMS_Project1_AshCMS.ear

    [11: 10:33] Application deployment...

    [11: 14:24] Application deployed successfully.

    [11: 14:24] time to deployment: 8 minutes, 11 seconds

    [11: 14:24]-deployment is complete.  ----

    what url in the browser.

    Concerning

    Mr President.

    I run my application on built-in web logic server and get the url from there

    http://localhost:7101 / ViewController/faces/MainPage

    then simply change the localhost of 7101 to 8081 as below

    http://localhost: 8081, ViewController, faces, MainPage

    and it works

    Concerning

  • How to find the child level for each table in a relational model?

    Earthlings,

    I need your help, and I know that, "Yes, we can change." Change this thread to a question answered.

    So: How to find the child level for each table in a relational model?

    I have a database of relacional (9.2), all right?
    .
         O /* This is a child who makes N references to each of the follow N parent tables (here: three), and so on. */
        /↑\ Fks
       O"O O" <-- level 2 for first table (circle)
      /↑\ Fks
    "o"o"o" <-- level 1 for middle table (circle)
       ↑ Fk
      "º"
    Tips:
    -Each circle represents a table;
    -Red no tables have foreign key
    -the picture on the front line of tree, for example, a level 3, but when 3 becomes N? How is N? That is the question.

    I started to think about the following:

    First of all, I need to know how to take the kids:
    select distinct child.table_name child
      from all_cons_columns father
      join all_cons_columns child
     using (owner, position)
      join (select child.owner,
                   child.constraint_name fk,
                   child.table_name child,
                   child.r_constraint_name pk,
                   father.table_name father
              from all_constraints father, all_constraints child
             where child.r_owner = father.owner
               and child.r_constraint_name = father.constraint_name
               and father.constraint_type in ('P', 'U')
               and child.constraint_type = 'R'
               and child.owner = 'OWNER') aux
     using (owner)
     where child.constraint_name = aux.fk
       and child.table_name = aux.child
       and father.constraint_name = aux.pk
       and father.table_name = aux.father;
    Thought...
    We will share!

    Thanks in advance,
    Philips

    Published by: BluShadow on April 1st, 2011 15:08
    formatting of code and hierarchy for readbility

    Have you looked to see if there is a cycle in the graph of dependence? Is there a table that has a foreign key to B and B has a back of A foreign key?

    SQL> create table my_emp (
      2    emp_id number primary key,
      3    emp_name varchar2(10),
      4    manager_id number
      5  );
    
    Table created.
    
    SQL> ed
    Wrote file afiedt.buf
    
      1  create table my_mgr (
      2    manager_id number primary key,
      3    employee_id number references my_emp( emp_id ),
      4    purchasing_authority number
      5* )
    SQL> /
    
    Table created.
    
    SQL> alter table my_emp
      2    add constraint fk_emp_mgr foreign key( manager_id )
      3         references my_mgr( manager_id );
    
    Table altered.
    
    SQL> ed
    Wrote file afiedt.buf
    
      1   select level lvl,
      2          child_table_name,
      3          sys_connect_by_path( child_table_name, '/' ) path
      4     from (select parent.table_name      parent_table_name,
      5                  parent.constraint_name parent_constraint_name,
      6                  child.table_name        child_table_name,
      7                  child.constraint_name   child_constraint_name
      8             from user_constraints parent,
      9                  user_constraints child
     10            where child.constraint_type = 'R'
     11              and parent.constraint_type = 'P'
     12              and child.r_constraint_name = parent.constraint_name
     13           union all
     14           select null,
     15                  null,
     16                  table_name,
     17                  constraint_name
     18             from user_constraints
     19            where constraint_type = 'P')
     20    start with child_table_name = 'MY_EMP'
     21*  connect by prior child_table_name = parent_table_name
    SQL> /
    ERROR:
    ORA-01436: CONNECT BY loop in user data
    

    If you have a cycle, you have some problems.

    (1) it is a NOCYCLE keyword does not cause the error, but that probably requires an Oracle version which is not so far off support. I don't think it was available at the time 9.2 but I don't have anything old enough to test on

    SQL> ed
    Wrote file afiedt.buf
    
      1   select level lvl,
      2          child_table_name,
      3          sys_connect_by_path( child_table_name, '/' ) path
      4     from (select parent.table_name      parent_table_name,
      5                  parent.constraint_name parent_constraint_name,
      6                  child.table_name        child_table_name,
      7                  child.constraint_name   child_constraint_name
      8             from user_constraints parent,
      9                  user_constraints child
     10            where child.constraint_type = 'R'
     11              and parent.constraint_type = 'P'
     12              and child.r_constraint_name = parent.constraint_name
     13           union all
     14           select null,
     15                  null,
     16                  table_name,
     17                  constraint_name
     18             from user_constraints
     19            where constraint_type = 'P')
     20    start with child_table_name = 'MY_EMP'
     21*  connect by nocycle prior child_table_name = parent_table_name
    SQL> /
    
           LVL CHILD_TABLE_NAME               PATH
    ---------- ------------------------------ --------------------
             1 MY_EMP                         /MY_EMP
             2 MY_MGR                         /MY_EMP/MY_MGR
             1 MY_EMP                         /MY_EMP
             2 MY_MGR                         /MY_EMP/MY_MGR
    

    (2) If you try to write on a table and all of its constraints in a file and do it in a valid order, the entire solution is probably wrong. It is impossible, for example, to generate the DDL for MY_EMP and MY_DEPT such as all instructions for a table come first, and all the instructions for the other are generated second. So even if NOCYCLE to avoid the error, you would end up with an invalid DDL script. If that's the problem, I would rethink the approach.

    -Generate the DDL for all tables without constraint
    -Can generate the DDL for all primary key constraints
    -Can generate the DDL for all unique key constraints
    -Can generate the DDL for all foreign key constraints

    This is not solidarity all the DOF for a given in the file object. But the SQL will be radically simpler writing - there will be no need to even look at the dependency graph.

    Justin

  • says that there is an update of firmware available for my 3 t time capsule. I get "an error occurred when downloading". How to find the problem?

    I said that there is an update of the firmware available for my 3 t time capsule. I get the message "an error occurred when downloading". How to find the problem? I have elcapitan 10.11.6 and capsule version 7.7.3

    Try temporarily, connect your MacBook Pro to your Time Capsule using an Ethernet connection... If not already, then try downloading the firmware again.

  • How to find the serial number of the processor in the MacBook pro s serial number? I have a dead MacBook that was given for service to a third party. I doubt that they have replaced the original parts. Help, please. Thank you

    How to find the serial number of the processor in the MacBook pro s serial number? I have a dead MacBook that was given for service to a third party. I doubt that they have replaced the original parts. Help, please. Thank you

    As far as I KNOW, the serial number of the MacBook does not have the serial number of the processor.

  • I make new the old id must paasward wen apple id I go passward, says your id or passward not at even I have received emails but get no email how to find the solution, I, m stuck wat to do

    I make new the old id must paasward wen apple id I go passward, says your id or passward not at even I have received emails but get no email how to find the solution, I, m stuck wat to do

    Have you tried to reset it in security issues? If you are not able to do so, contact Apple support so a security identifier Apple Advisor can help you. 800-275-2273.

  • How to find the date item was my favorites on Mozilla Firefox

    on system moot bookmark how to find the date of the bookmark?

    In bookmarks menu select organize bookmarks to open the bookmarks library. In the bookmarks library, click views, and then display the columns and then added. This will display a column showing when a bookmark has been added.

  • How to find the owners of icloud id?

    IM new to this thing from icloud, I bought 3 old ipads2 on a flea market, where unlocked 2 but we have icloud, the screen is not the old owner alone info [email protected], I don't have a problem, try contacting the owner, but how to find the id of owner? even if is a stolen ipad that I'll be more than returned gad, or ask the owner to remove icloud, but without the owner info is difficult, any advice will be apreciated, thanks

    You can not find it. Go back on the market and claim a refund for the iPad.

    (140442)

Maybe you are looking for

  • How to place an update?

    I've recently updated to 10.11.6 El captin on my Mac book Pro MD101HN/A. Please can someone install me operating system previous OSX version? I have enough well don't like this, it drains the power. Thank you Tejas < link published by host >

  • Lenovo Yoga 8 (B6000) may screenshot?

    Hey, Lenovo Fan I just bought this camera last month and I don't know how I can screenshot I just found how to activate the development tools for this but can't always screenshot and this device can take root or not Thxs a lot and the best account fo

  • Intrusion of Winup asks as screensaver

    someone broke into application version 3.3.6.1 winup as application screen saver in my hpmini book that it is not deleted. How to remove

  • writing from the end of the file - FileConnection or PrintOutPutStream

    Hi allIm a new developer of blackberry and I were assigned to make a newspaper for the app I'm working on. The newspaper is supposed to be written to a file, but whenever the application is run, the new content is not meant to replace the old.The thi

  • Smartphones blackBerry how to remove all entries from the calendar on a BB Pearl 8110?

    I would like to delete all the entries in my calendar on my pearl - history, present and future - is possible to do it for all the calendar without having to individually delete entries? Thank you