Getting 2nd Least Value from Different Column

Hi there All,
I have one odd requirement.
I hava table which has diffrent columns of numeric Datatype.
The task is to get the least values from the table.
I can take the least value by least(col1,col2,col3 ...) function.Until this stage it is fine.
But also I have take 2nd least value and 3rd least value, which I am quite unsure how to get it.
Looking forward for suggestions.
Thanks in Advance.
Regards,
Ajeet

The following is a generic solution that will allow you to select the nth least and allow you to pass as many column names as you like and will return null if the nth least requested exceeds the number of distinct values. The nleast function that I wrote uses the str2tbl function by Tom Kyte. I have included a demonstration of its usage below. The value returned for the 1st least is the same as that returned by the least function.
This should have been posted on the SQL and PL/SQL discussion group of these forums, rather than the general database. I also posted the same response in the SQL discussion group of the Orafaq forums.
scott@ORA92> -- test data:
scott@ORA92> SELECT * FROM your_table
  2  /
      COL1       COL2       COL3
         1          2          3
         4          6          5
         8          7          9
        11         12         10
        15         13         14
        18         17         16
6 rows selected.
scott@ORA92> -- type and functions:
scott@ORA92> create or replace type myTableType as table of number;
  2  /
Type created.
scott@ORA92> create or replace function str2tbl( p_str in varchar2 )
  2  return myTableType
  3  as
  4        l_str      long default p_str || ',';
  5        l_n         number;
  6        l_data    myTableType := myTabletype();
  7  begin
  8        loop
  9            l_n := instr( l_str, ',' );
10            exit when (nvl(l_n,0) = 0);
11            l_data.extend;
12            l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
13            l_str := substr( l_str, l_n+1 );
14        end loop;
15        return l_data;
16  end;
17  /
Function created.
scott@ORA92> CREATE OR REPLACE FUNCTION nleast
  2    (p_n        IN NUMBER,
  3       p_nums        IN VARCHAR2)
  4    RETURN           NUMBER
  5  AS
  6    v_nleast      NUMBER;
  7  BEGIN
  8    SELECT DISTINCT column_value
  9    INTO   v_nleast
10    FROM   (SELECT column_value,
11                  DENSE_RANK () OVER (ORDER BY column_value) AS num_rk
12              FROM   (select *
13                   from   table (CAST (str2tbl (p_nums) AS mytabletype)))
14             WHERE   column_value IS NOT NULL)
15    WHERE  num_rk = p_n;
16    RETURN v_nleast;
17  EXCEPTION
18    WHEN OTHERS THEN RETURN NULL;
19  END nleast;
20  /
Function created.
scott@ORA92> SHOW ERRORS
No errors.
scott@ORA92> -- query:
scott@ORA92> SELECT col1, col2, col3,
  2           LEAST (col1, col2, col3) AS the_least,
  3           nleast (1, col1 || ',' || col2 || ',' || col3) AS first_least,
  4           nleast (2, col1 || ',' || col2 || ',' || col3) AS second_least,
  5           nleast (3, col1 || ',' || col2 || ',' || col3) AS third_least,
  6           nleast (4, col1 || ',' || col2 || ',' || col3) AS fourth_least
  7  FROM   your_table
  8  /
      COL1       COL2       COL3  THE_LEAST FIRST_LEAST SECOND_LEAST THIRD_LEAST FOURTH_LEAST
         1          2          3          1           1            2           3
         4          6          5          4           4            5           6
         8          7          9          7           7            8           9
        11         12         10         10          10           11          12
        15         13         14         13          13           14          15
        18         17         16         16          16           17          18
6 rows selected.

Similar Messages

  • Get the Cookie Value from Different Application Servers

    Hi All,
    I am using the two applications with different application servers. How to get the cookie values from one to another application. Shall i know any sample codes?
    Thanks
    Maalan

    A cookie carries a domain name. The browser will only return cookies whose domain matches to domain to which the request is made, however although you can use a partial domain name providing it's not too generic. So, when you add a cookie you need to explicitly set the domain name on the cookie to, for example, your company suffix like ".acme.com", then the cookie should be returned to all the servers under that domain e.g. server1.acme.com and server2.acme.com.

  • Get millisecond values from timestamp column in v$logmnr_contents

    Hello
    How do we get millisecond values from timestamp column in v$logmnr_contents.
    I tried with following query.
    select scn,To_Char(timestamp,'DD-MON-YYYY HH24:MI:SS:FF') from v$logmnr_contents WHERE OPERATION NOT IN('START') and username ='SCOTT' and sql_redo is not null and (seg_owner is null or seg_owner not in('SYS'));
    it says ORA-01821: date format not recognized. I want to find the relation of scn with timestamp. In forums i found, scn is derived from timestamp value. I dont know its correct or not.
    if i query with out FF in time format i get like
    scn timestamp
    808743 27-NOV-2007 00:12:53
    808743 27-NOV-2007 00:12:53
    808743 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    if scn is derived from timestamp with milliseconds, each scn should be different right?More help please

    May be there's an easy way solving your problem, I did it like that:
    CREATE TABLE quota_test (test VARCHAR2(50))
    INSERT INTO quota_test
    VALUES ('update "SCOTT"."NEWTAB1" set a="34" and b="45"')
    SELECT test normal, REPLACE(SUBSTR(test,INSTR(test,'"',1),INSTR(test,'.',1)+2),'"','') changed
    FROM quota_test
    Result is :
    NORMAL
    update "SCOTT"."NEWTAB1" set a="34" and b="45"      
    CHANGED
    SCOTT.NEWTAB1
    If you didn't understand, I can explain what I wrote

  • From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    Hi,
    Use NVL or COALESCE:
    NVL (col_a, col_b)
    Returns col_a if col_a is not NULL; otherwise, it returns col_b.
    Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
    For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Retrieving multiple values from one column in SELECT statement

    Hi,
    I have a slight dilemma in that I'm trying to pull down all the values from a column from a select statement that includes some JOINS in it.
    If I run the query at the SQL Plus prompt, it pulls back all the values/rows.
    When I run the select (and prepared ) statement in my JSP, it only pulls back one of the 4 values I'm trying to retrieve.
    e.g.
    at the DB level :
    SELECT role_name, CC_ID FROM votetbl a
    INNER JOIN APPROVERS b ON
    a.BUSVP = b.BUSVP AND
    a.BRANCH = b.BRANCH
    WHERE CC_ID = 1688this will return:
    ROLE_NAME CC_ID
    ops 1688
    ops 1688
    comply 1688
    legal 1688
    comply 1688
    When run in my JSP, like so:
    String primID3a = request.getParameter("primID");
    Statement stmtovoter = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String prepvotSQL = "SELECT role_name, CC_ID FROM votetbl a INNER JOIN APPROVERS b ON a.BUSVP = b.BUSVP AND " +
                         "a.BRANCH = b.BRANCH WHERE CC_ID = ?";
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    out.println("Vote category: "+votecat);I only get ops returned.
    Do I need to run an enumerator? Or reqest.getParameterValues or use a while statement around the results set?
    Any feedback and direction here is welcomed!
    Thanks!

    Actually, I tried looping and still only get 1, but returned several times.
    i.e.
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    while (rest3.next()) {
    out.print("category roles "+votecat);
    }then I get returned the following:
    admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admin
    like so.
    Where as at the DB level I get
    ROLE_NAME CC_ID
    admin 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    risk 1688
    comply 1688
    legal 1688
    legal 1688
    ops 1688
    comply 1688
    Maybe the while should go around the getString(1) designation? But I was thinking I'd tried that and gotten invalid cursor error
    Something is definitely amiss, between the prepared statement in the servlet and the SELECT statement at the DB level.
    I can totally hardcode the statement in the servlet or JSP and it will return one value potentially several times, but only one.
    Other times, it will not return a value at all, even though one resides in the db.
    Yet go to the DB/SQL Plus prompt and it returns perfectly. I can simply copy and paste the SELECT statement from the out.print line I made and it works like a champ in SQL Plus. Any ideas why the same exact thing cannot return the proper values within the servlet/JSP?
    Yeeeeeeesh!!! : (
    Message was edited by:
    bpropes20

  • How to get edited row values from ADF table?

    JDev 11.
    I have a table which is populated with data from Bean.
    I need to save changes after user make changes in any table cell. InputText is defined for table column component.
    I have defined ValueChangeListener for inputText field and AutoSubmit=true. So when user change value in inputText field, method is called:
    public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
    getSelectedRow();
    SaveMaterial(material);
    This method should call getSelectedRow which take values from selected table row and save them into object:
    private Row getSelectedRow(){
    RichTable table = this.getMaterialTable();
    Iterator selection = table.getSelectedRowKeys().iterator();
    while (selection.hasNext())
    Object key = selection.next();
    table.setRowKey(key);
    Object o = table.getRowData();
    material = (MATERIAL) o;
    System.out.println("Selected Material Desc = "+material.getEnumb());
    return null;
    Problem is that getSelectedRow method doesnt get new (edited) values, old values are still used.
    I have tried to use ActiveButton with same method and it works fine in that case. New values are selected from active row and inserted into object.
    JSF:
    <af:table var="row" rowSelection="single" columnSelection="single"
    value="#{ManageWO.material}" binding="#{ManageWO.materialTable}">
    <af:column sortable="false" headerText="E-number">
    <af:inputText value="#{row.enumb}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
    </af:column>
    <af:column sortable="false" headerText="Description">
    <af:inputText value="#{row.desc}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
    </af:column>
    </af:table>
    <af:activeCommandToolbarButton text="Save" action="#{ManageWO.EditData}"/>
    What is a correct place from where save method should be called to get new (edited) values from ADF table?
    Thanks.

    Did you look into the valueChangeEvent?
    It has oldValue and newValue attributes.
    public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
    Object oldVal = valueChangeEvent.getOldValue();
    Object newVal = valueChangeEvent.getNewValue();
    // check if you see what you are looking for.....
    getSelectedRow();
    SaveMaterial(material);
    }Timo

  • How to get all the values in one column of a JTable

    How to get all the values in one column of a JTable as a Collection of String.
    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.

    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.

  • Reading values from lookup columns through custom workflow in SharePoint 2013

    We are able to read the values of text, number columns through custom workflow (via coding) in SharePoint 2013. However, we are not able to read values from lookup columns. So, request anyone to provide help on this.
    Thanks & regards,
    Aditya

    Hi,
    According to your post, my understanding is that you want to read values from lookup columns through custom workflow in SharePoint 2013.
    Since the workflow just doesn't get lookup fields, let's give it something static to work with instead. If we can capture the ID of the lookup field and store that as a static value in our list, the workflow can happily use that to look up our related.
    For more information, you can refer to:
    SharePoint 2013 Workflows and Lookup Columns
    Thanks,
    Linda Li                
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Linda Li
    TechNet Community Support

  • Passing value from Report Column to Javascript

    Dear Apex wizards,
    I am a bit stuck right now with implementing a modal pop-up/iframe/javascript and this forum is my last hope to fix this issue.
    Anyway, will try to explain what I am trying to accomplish.
    What I need is: I want to have an SQL report, as a very first column I want to have an "ID" numbers from my table and I want this column to have a "Column Link" set in "Column Attributes" proper ties. The trick is, that when I click on the column link (when I run my report on Apex page) I need a JQuery modal window to pop-up where in IFrame will be another page and this page will use an "ID" from my column link URL to display data. So, basically I want to pass an "ID" value from my parent page to my child page which is displayed in iFrame of modal window.
    And here is what I have:
    1. I do have an SQL report:
    select SUBNET_ID,
           long2ip(NETWORK_ADDRESS),
           long2ip(SUBNET_MASK),
           long2ip(END_HOST),
           long2ip(START_HOST),
           MAX_HOSTS,
           long2ip(BROADCAST_IP),
           NETWORK_CLASS,
           NETWORK_SIZE,
           HOST_SIZE
    from   YC_CM_IP_SUBNETS 2. Then, in "Column Attributes" for "SUBNET_ID" a have set a "Column Link" to URL as : javascript:ViewNetworkDetails(#SUBNET_ID#); 3. Now, when I run my page and point my mice on any item in my "SUBNET_ID" column I can see that it is getting a "SUBNET_ID" number from my table and it shows it in the buttom of the browser as :javascript:ViewNetworkDetails(1);, or (2) or whatever "SUBNET_ID" is. So, that is good.
    4. And here I am getting confused, basically I have to pass a value of javascript:ViewNetworkDetails(#SUBNET_ID#);, which seems to work as it gives me correct numbers from my table, to my "ViewNetworkDetails" JavaScript function, so it can paste this value into "f?p=........." iFrame URL. Below is my Jquery Modal form script and Javascript to redirect me to my popup page (the script is in HTML Header):
    <script type="text/javascript">
    function ViewNetworkDetails(){
    var apexSession = $v('pInstance');
    var apexAppId = $v('pFlowId');
    var subnetIDNumber = document.getElementById(#SUBNET_ID#);
    $(function(){
    vRuleBox = '<div id="ViewNetworkDetailsBox" title="View Subnet Details">
    <iframe src="f?p='+apexAppId+':103:'+apexSession+'::NO:103:P103_SUBNET_ID:'+subnetIDNumber+'
    "width="875" height="500" title="View Subnet Details" frameborder="no"></iframe></div>'
    $(document.body).append(vRuleBox);
    $("#ViewNetworkDetailsBox").dialog({
                            buttons:{"Cancel":function(){$(this).dialog("close");}},
                            stack: true,
    modal: true,                            
                            width: 950,                    
    resizable: true,
    autoResize: true,
    draggable: true,
    close : function(){$("#ViewNetworkDetailsBox").remove();
                            location.reload(true); }
    </script> P.S. My assumption is, that there is a problem with this part of my scriptvar subnetIDNumber = document.getElementById(#SUBNET_ID#); where I cannot get my "SUBNET_ID" value from javascript:ViewNetworkDetails(#SUBNET_ID#); into "subnetIDNumber" variable and that is why I cannot pass it to my iFrame URL.
    P.S. P.S. the child page 103 has a "Automated Row Fetch", so it is not a problem. In addition, I did a simple test, where I had a page item "P102_Value" with some value and in my script I had instead var subnetIDNumber = document.getElementById(#SUBNET_ID#); this var subnetIDNumber = $v('P102_Value'); and it worked perfectly fine....but cannot make it working against SQL Select statement :-(
    HEEEEEEEEEEEEEELLLLLPPPP.
    Thanks

    Change your column link to send the subnet_id column's value to the function call (you mentioned it, but I m not sure if you actually did)
    javascript:ViewNetworkDetails(#SUBNET_ID#);<u>You are passing the parameter value to the function, but not defined any parameters in the function definition</u>(this is possible in JS, any extra parameters is ignored)
    So, modify the function to accept the subnet ID parameter(I am actually surprised how you missed this) and assign that parameter to variable.
    <script type="text/javascript">
    function ViewNetworkDetails(pSubnetId){
    var apexSession = $v('pInstance');
    var apexAppId = $v('pFlowId');
    var subnetIDNumber = pSubnetId;
    //rest of the code would be the same

  • How can i get the all values from the Property file to Hashtable?

    how can i get the all values from the Property file to Hashtable?
    ok,consider my property file name is pro.PROPERTIES
    and it contain
    8326=sun developer
    4306=sun java developer
    3943=java developer
    how can i get the all keys & values from the pro.PROPERTIES to hashtable
    plz help guys..............

    The Properties class is already a subclass of Hashtable. So if you have a Properties object, you already have a Hashtable. So all you need to do is the first part of that:Properties props = new Properties();
    InputStream is = new FileInputStream("tivoli.properties");
    props.load(is);

  • Get all the values from a multiple select in a multipart form

    Hi there!
    I am using a form with enctype="multipart/form-data" in order to upload files from the form.
    I have read this page: http://commons.apache.org/fileupload/using.html and everything works well for my form.
    The only problem is that I can't get all the values from a "multiple select" html object. I get only one value.
    Using servlets I have used this method:
    public java.lang.String[] getParameterValues(java.lang.String name) But now I have enctype="multipart/form-data" in my form and I can't use this way...
    Is there a way to get all the values of a multi-valued parameter?
    Thanks a lot!
    Stefano

    Hi
    I have got solution for this problem so, I am listing here logic
    assume tag name of html
    <select name="moption" multiple="multiple">
    iterate it in as
    String moption="";
    boolean cnt=true;
    while(itr.hasNext())
    FileItem fi=(FileItem)itr.next();
    if(fi.isFormField())
    if(fi.getFieldName().equals("moption"))
    if(cnt==true)
    moption=fi.getString();
    cnt=false;
    else
    moption=moption+","+fi.getString();
    If wants more help then mail me your problem
    at [email protected]
    Thanks!
    Anand Shankar
    Edited by: AnandShankar on 6 Nov, 2009 12:54 PM

  • How to get all the values from the dropdown menu

    How to get all the values from the dropdown menu
    I need to be able to extract all values from the dropdown menu; I know how to get all those values as a string, but I need to be able to access each item; (the value in a dropdown menu will change dynamically)
    How do I get number of item is selection dropdown?
    How do I extract a ?name? for each value, one by one?
    How do I change a selection by referring to particular index of the item in a dropdown menu?
    Here is the Path to dropdown menu that I'm trying to access (form contains number of similar dropdowns)
    RSWApp.om.GetElementByPath "window(index=0).form(id=""aspnetForm"" | action=""advancedsearch.aspx"" | index=0).formelement[SELECT](name=""ctl00$MainContent$hardwareBrand"" | id=""ctl00_MainContent_hardwareBrand"" | index=16)", element
    Message was edited by: testtest

    The findElement method allows various attributes to be used to search. Take the following two examples for the element below:
    <Select Name=ProdType ID=testProd>
    </Select>
    I can find the element based on its name or any other attribute, I just need to specify what I am looking for. To find it by name I would do the following:
    Set x = RSWApp.om.FindElement("ProdType","SELECT","Name")
    If I want to search by id I could do the following:
    Set x = RSWApp.om.FindElement("testProd","SELECT","ID")
    Usually you will use whatever is available. Since the select element has no name or ID on the Empirix home page, I used the onChange attribute. You can use any attribute as long as you specify which one you are using (last argument in these examples)
    You can use the FindElement to grab links, text boxes, etc.
    The next example grabs from a link on a page
    Home
    Set x = RSWApp.om.FindElement("Home","A","innerText")
    I hope this helps clear it up.

  • List values from different prompts into one.

    Hi All,
    We have OBIEE 11g and building Analysis out of Essbase cube. Here is our Requirement we need to build a Dashboard prompt which shows values from different tables.
    All these tables belong to one dimension and this has about 10 tables in it. So the prompt which we build should pick specific values from each table.
    I know we can build prompt for every table which we will end up with 10 prompts which doesn't look good so we need to show all the values of these ten prompts in single drop down (One Prompt)which we can use for refreshing the dashbaord.
    Say we have table names as Gen1.Organisation, Gen2.Organisation,.........Gen10.Organisation
    Thanks,
    Shashank

    are there any dependancies on the selections e.g if you pick Gen1.Organisation1 does this mean that you can only pick Gen2.OrgA or Org B?
    if there are no dependancies and you want all possible combinations across ten tables then you are looking at one huge drop down list !!

  • How to get the return values from a web page

    Hi all :
       how to get the return values from a web page ?  I mean how pass values betwen webflow and web page ?
    thank you very much
    Edited by: jingying Sony on Apr 15, 2010 6:15 AM
    Edited by: jingying Sony on Apr 15, 2010 6:18 AM

    Hi,
    What kind of web page do you have? Do you have possibility to for example make RFCs? Then you could trigger events (with parameters that could "return" the values) and the workflow could react to those events. For example your task can have terminating events.
    Regards,
    Karri

  • Getting all the values from a JList

    Hi,
    I want to get all the values from a JList and store it into an array. Any method is available to perform this task? Pls help me out with this task.

    Use getModel() on the list to get the ListModel and then call getSize() and getElementAt(int) to loop over the elements
    HTH
    Mike

Maybe you are looking for

  • HP Laserjet 4P Printing Problems

    I am using a Mac G4 with 10.4.7 and printing on a HP Laser Jet 4P using driver HP Laser Jet 4 Series Gimp. When I first print a page or 20 pages of the job, all works fine. Once I go to print another job, I get the msg "GIMP Printing Page 1, 15% and

  • CSS for links display differently in Safari and Firefox

    Hello all, I am having some link display problems. The CSS code for my link display is as follows: #sidebar_1 a{ text-decoration: none; font-weight: bold; #sidebar_1 a:link{ color: #CCC; #sidebar_1 a:visited{ color: #000; #sidebar_1 a:hover, #sidebar

  • E N A B L E R - -  W A N T E D ! ! !

    Okay, how do we get the precious 802.11n Enabler? I'm looking forward to installing it.

  • [SOLVED] Prevent racy mounting when booting

    Hey there! When booting I mount an external (encrypted) drive by the means of fstab (and crypttab) under a directory which is only accessible by root.  In order to allow read-only access for users, I remount the the device under another directory whi

  • Lightroom 3  lightroom 4

    If I have a lightroom 3 catalog can I open it in lightroom 4 or will I use my settings