GROUP BY doubt

Hi All,
I am aware that what ever column we select we will have to enter it in group by clause if we perform aggregate function in select statement. in my below query, i am trying to give group by column position like (group by 1,2,3). but its not working. its still keeps on telling "ORA-00979: not a GROUP BY expression"
can you please help me with this? how i should place group by with the columns in select statement with position?
WITH user_lang_permsn
AS
   (SELECT ur.lang_id
    FROM permsn_t per
    INNER JOIN role_permsn_t rp
    ON   rp.permsn_id = per.permsn_id
    INNER JOIN usr_role_t ur
    ON   ur.role_id = rp.role_id
    WHERE ur.usr_id = 1
    AND   per.permsn_name = 'LanguageTranslation'
    UNION
    SELECT upm.lang_id
    FROM   permsn_t p
    INNER JOIN usr_permsn_t upm
    ON    upm.permsn_id = p.permsn_id
    WHERE upm.usr_id = 1
    AND   p.permsn_name = 'LanguageTranslation'
    UNION
    SELECT f_get_central_language
    FROM   dual)
    SELECT c.chr_code "char code",
                         f_char_dscr(pl.prpsd_chr_id,   dc.dscr_id,   1) "characteristic type",
                         count(cvd.chr_val_id),
                         cvd.chr_val_dscr,
                         CASE
                              WHEN l.lang_id = f_get_central_language THEN
                                 NULL
                              ELSE
                                 l.lang_dscr
                              END
                         AS lang_dscr,
                         CASE
                              WHEN (cvd.lang_id = f_get_central_language AND cvd.trans_st = 'P') THEN
                                   'N'
                              WHEN cvd.chr_val_dscr IS NULL THEN
                                   'N'
                              ELSE
                                   'Y'
                              END
                         AS display
                  FROM  prpsl_lst_t pl --,      user_lang_permsn ulp
                  INNER JOIN chr_t c
                  ON    pl.prpsd_chr_id  = c.chr_id
                  INNER JOIN dscr_config_t dc
                  ON    dc.rgn_id        = c.rgn_id
                  AND   dc.enty_dscr     = 'CHARACTERISTIC'
                  AND   dc.main_dscr_ind = 'Y'
                  INNER JOIN dscr_config_t cdc
                  ON    cdc.rgn_id        = c.rgn_id
                  AND   cdc.enty_dscr     = 'CHR_VAL'
                  AND   cdc.main_dscr_ind = 'Y'
                  CROSS JOIN user_lang_permsn ulp
                  INNER JOIN chr_val_dscr_t cvd
                  ON    cvd.chr_val_id    = pl.prpsd_chr_val_id
                  AND   cvd.dscr_id       = cdc.dscr_id
                  AND   cvd.lang_id       = ulp.lang_id
                  INNER JOIN lang_t l
                  ON    l.lang_id         = cvd.lang_id
                  WHERE pl.prpsl_status_ref_id = pkg_grd_global.F_GET_REF_ID_BY_VAL('PROPOSED','STATUS')
                  AND EXISTS
(SELECT 'e' --product groups related to the proposed char value
                                FROM   prpsl_attr_t pa
                                INNER JOIN usr_chr_val_assoc_t ucv -- user scope
                                ON     ucv.chr_val_id           = pa.prpsl_attr_val_id
                                WHERE  pa.prpsl_id              = pl.prpsl_id
                                AND    pa.prpsl_attr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('PRODUCTGROUP',   'PROPOSAL ATTRIBUTE TYPE')
                                AND    ucv.usr_id               = 1)
                                AND  EXISTS
                                (SELECT 'e' -- language permission check
                                FROM   prpsl_attr_t pa
                                INNER JOIN user_lang_permsn up
                                ON     up.lang_id = pa.prpsl_attr_val_id
                                WHERE  pa.prpsl_id              = pl.prpsl_id
                                AND    pa.prpsl_attr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('LANGUAGE',   'PROPOSAL ATTRIBUTE TYPE'))
                                AND  EXISTS (SELECT 'e' -- language permission check
                                FROM   prpsl_attr_t pa
                                INNER JOIN
                                       (SELECT ur.rgn_id
                                        FROM permsn_t per
                                        INNER JOIN role_permsn_t rp
                                        ON   rp.permsn_id = per.permsn_id
                                        INNER JOIN usr_role_t ur
                                        ON   ur.role_id = rp.role_id
                                        WHERE ur.usr_id = 1
                                        AND   per.permsn_name = 'LanguageTranslation'
                                        UNION
                                        SELECT upm.rgn_id
                                        FROM   permsn_t p
                                        INNER JOIN usr_permsn_t upm
                                        ON    upm.permsn_id = p.permsn_id
                                        WHERE  upm.usr_id = 1
                                        AND    p.permsn_name = 'LanguageTranslation') up
                                ON     up.rgn_id = pa.prpsl_attr_val_id
                                WHERE  pa.prpsl_id              = pl.prpsl_id
                                AND    pa.prpsl_attr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('COUNTRY',   'PROPOSAL ATTRIBUTE TYPE'))
                                GROUP BY cvd.chr_val_id,c.chr_code,f_char_dscr(pl.prpsd_chr_id,   dc.dscr_id,   1),cvd.chr_val_dscr
                                        

user 777111 wrote:
Hi All,
I am aware that what ever column we select we will have to enter it in group by clause if we perform aggregate function in select statement. in my below query, i am trying to give group by column position like (group by 1,2,3). but its not working. its still keeps on telling "ORA-00979: not a GROUP BY expression"
can you please help me with this? how i should place group by with the columns in select statement with position? I believe you can not use positional references in GROUP BY. You have to use column names. So a "group by 1,2,3" results in grouping by constant values. (and hence the error)
You can use positional references in ORDER BY.

Similar Messages

  • Using GROUP BY Doubt

    Eg: i have an employees table
    With CURADDRIND 0's and 1's and CREATEDATE is a DATE Column
    i want to query and get the Latest CURRADDRIND for a particular employee for the maximum of CREATE DATE
    I Have data like this
    empid curraddrind createdte
    130 0 9/10/2008
    130 1 9/15/2008
    130 0 8/15/2008
    i want output
    1 9/15/2008
    i wrote query like this
    select curraddrind,max(createdte) from emp
    where empid=130
    group by curraddrind
    i am getting
    1 9/15/2008
    0 9/10/2008-->this also ..but shud be omitted
    can anyone give solution for this ..
    Thanks in advance

    Or using only one table access:
    SQL> create table t (empid,curraddrind,createdte)
      2  as
      3  select 130, 0, date '2008-09-10' from dual union all
      4  select 130, 1, date '2008-09-15' from dual union all
      5  select 130, 0, date '2008-08-15' from dual
      6  /
    Table created.
    SQL> select max(curraddrind) keep (dense_rank last order by createdte) curraddrind
      2       , max(createdte) createdte
      3    from t
      4   where empid = 130
      5  /
    CURRADDRIND CREATEDTE
              1 15-09-2008 00:00:00
    1 row selected.Regards,
    Rob.

  • CSA 5.1 test mode to protect mode conversion

    Dear Netpros,
    I installed the CSA 5.1 both desktop and server test mode agent kits. Now how can i convert it to real protect mode.Also let me understand the learn mode concept.
    Thanks
    swami

    hi tom i am new to csa.
    i have learnd abt the test mode is that. after selecting the test mode in a group . all the actions will be allowed by the csa agent even though the actions are denied in the policies applied to the group.
    main doubt is in learn mode is that .
    in learn mode is it the same???. i mean as per the documentation they have only mentioned that the rules in which the action is set to query the user in learn mode it will not query the user rather allow the action for the query responses.
    what abt the rules in which the action is set to deny or terminate. will these actions be taken in learn mode or since learn mode is applied on the group all the actions to the rules will be set to query the user .
    this is not mentioned any where.
    can u pls help me out.
    regards
    sushil

  • IPad ios6 update Chinese keyboard option missing dynamic selection in zhuyin

    After update my iPad to ios6, the zhyin has different keyboard layout. I was told to switch the option to dynamic so I can switch back to the old way.  But I don't see such selection when I am in general -> keyboard -> Chinese traditional zhuyin-> zhuyin (only selection I have)
    Help?

    You may want to search/ask in the Chinese Mac group, I doubt there is any fix other than asking Apple to change it.
    https://groups.google.com/forum/?fromgroups#!forum/chinesemac
    http://www.apple.com/feedback/ipad.html

  • Doubt in Group by

    I have doubt in group by clause.
    System_log table contains
    server_id,
    system_cpu,
    user_cpu,
    time_log
    as fields
    I want to display distinct servers order by (system+user)
    SELECT server_id
    FROM system_log
    WHERE time_log IN (SELECT MAX(time_log)
    FROM system_log
    GROUP BY server_id)
    ORDER BY (system+ user) ASC
    In this query, i'm not getting distinct server_id.
    Can anyone correct me this query?

    Try
    SELECT sl.server_id
      FROM system_log sl
    WHERE time_log =
           (SELECT MAX(time_log) FROM system_log sl2 WHERE sl.server_id = sl2.server_id GROUP BY server_id)or
    SELECT sl2.server_id
      FROM (SELECT sl.*
                  ,ROW_NUMBER() over(PARTITION BY sl.server_id ORDER BY sl.time_log DESC) RN
              FROM system_log sl) sl2
    WHERE sl2.rn = 1Regards...

  • Doubts Employee group

    Good Afternoon,
    I have a doutbs,
    When HR run an action of leave of an employee, the field Employee group have that be changed to Retired or not?, or only with the status of employment P0000-STAT2(0 Withdrawn) is necessary?.
    I want know , what is the better practice?
    Regards.

    Hi, Kapil Kaushal , Sikindar 
    The system work fine with the field P0000-STAT2, because i have configured the feature MSN 31 in the table T529A for the action of leave. and in the leave the system automatically change the status to Withdrawn.
    I want know if the field PERSG also i have that change to retire or not is necessary ?
    I am changing in the action of leave this field PERSG , but a consultant said that not is necessary, and i want kown ¿what is the best practice?
    This is the doubt.

  • Doubt in Selection-Screen for Program type "Function Group"

    Hi Gurus,
    I created a Function group in that i created one screen and writtem the Screen flow logic. In that screen I called a Function module "COMPLEX_SELECTIONS_DIALOG" For Creating a selection-Screen.
    The code snippet is like below.
    CASE ok_code .
        WHEN c_clk1.
          CALL FUNCTION 'COMPLEX_SELECTIONS_DIALOG'
         EXPORTING
           title                   = text-002
           text                    = 'Material Number'
           signed                  = 'X'
            lower_case              = ' '
            no_interval_check       = ' '
             just_display            = ' '          " Un commented by Srihari
             just_incl               = 'X'          " Un commented by Srihari
            excluded_options        =
            description             =
            help_field              =
            search_help             =
           tab_and_field           = st_tab
          TABLES
            range                   = r_matnr
         EXCEPTIONS
           no_range_tab            = 1
           cancelled               = 2
           internal_error          = 3
           invalid_fieldname       = 4
           OTHERS                  = 5.
    it works fine. But the problem is if i click the multiple selection button for the select-option in selection screen and enter the values and copy those value. In the multiple selection button green button is not coming like noram report selection-screen. Please remember I used the program type as "Function Group" not "Module Pool".
    Please send your suggestions.
    Thanks,
    Srihari.

    Ok, I am not 100% sure, if I understand you correctly, you said, you created one screen to 'simulate' a standard selection screen behavior without using select-options statement?
    If that's not correct, could you please post a few more details on what exactly you are doing.
    I had to 'simulate' a select-option behavior which I did as follows:
    - I created a range variable to store the values (s_ctby)
    - on the screen I defined the LOW (s_ctby-low), HIGH (s_ctby-high) and the multiple selection field pushbutton
    - In the PBO I set the icons for the multiple selection pushbutton
      READ TABLE s_ctby INDEX 2 TRANSPORTING NO FIELDS.
      IF sy-subrc NE 0.
        gv_createby = gc_icon_enter_data.
      ELSE.
        gv_createby = gc_icon_disp_data.
      ENDIF.
    - In the PBO make sure that any values entered on the screen are transferred to the range
    * transfer any changed values into the correct range for user transaction
    * (screen 0110) because that screen just 'simulates' a selection screen
    * so we have to make sure that any data the user enters in the selection
    * fields is passed into the appropriate ranges
      IF sy-tcode EQ gc_trans_user.
    *   created by
        IF NOT s_ctby-high IS INITIAL.
          s_ctby-sign   = c_i.
          s_ctby-option = c_bt.
          IF s_ctby[] IS INITIAL.
            INSERT s_ctby INDEX 1.
          ELSE.
            MODIFY s_ctby INDEX 1.
          ENDIF.
        ELSEIF NOT s_ctby-low  IS INITIAL AND
                   s_ctby-high IS INITIAL.
          s_ctby-sign   = c_i.
          s_ctby-option = c_eq.
          IF s_ctby[] IS INITIAL.
            INSERT s_ctby INDEX 1.
          ELSE.
            MODIFY s_ctby INDEX 1.
          ENDIF.
        ELSEIF s_ctby-low  IS INITIAL AND
               s_ctby-high IS INITIAL.
          DELETE s_ctby INDEX 1.
        ENDIF.
    - If the user hits the multiple selection pushbutton
        WHEN gc_fc_create_by.
    *     if the user hits the multiple selection button on the screen
    *     we call the standard SAP functionality to show the multiple
    *     selection popup SAP uses on a standard selection screen
          CALL FUNCTION 'COMPLEX_SELECTIONS_DIALOG'
            EXPORTING
              title             = text-t02
            TABLES
              range             = s_ctby
            EXCEPTIONS
              no_range_tab      = 1
              cancelled         = 2
              internal_error    = 3
              invalid_fieldname = 4
              OTHERS            = 5.
          IF sy-subrc NE 0 AND NOT sy-msgty IS INITIAL.
            MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
          ENDIF.
    *     now update the header line so the screen fields display the correct values
          CLEAR s_ctby.
          READ TABLE s_ctby INDEX 1.
    Hope that helps,
    Michael

  • Doubt regarding avoiding group by function

    i just came to know about a query which will avoid group by function,
    select sum(column_name) over ( partition by <coulmns> order by <solumns> )
    from <table_name>
    now columns specified in the partition by clause, are the one which will be specified under group by clause, i know this works, but can anyone expalain the meaning and significance of over keyword and is it a function, i mean with respect to SQL language that syntax seems to be very much different isn't it???
    cheere

    Hi
    Analytic functions are not alternative for group by.
    Analytic functions are the last set of operations performed in a query except for the
    final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
    And regarding your question,
    see this example from oracle documentation
    The following example calculates, for each manager in the sample table
    hr.employees, a cumulative total of salaries of employees who answer to that
    manager that are equal to or less than the current salary. You can see that Raphaely and Cambrault have the same cumulative total. This is because Raphaely and Cambrault have the identical salaries, so Oracle adds together their salary values and applies the same cumulative total to both rows.
    SELECT manager_id, last_name, salary,
    SUM(salary) OVER (PARTITION BY manager_id ORDER BY salary
    RANGE UNBOUNDED PRECEDING) l_csum
    FROM employees;
    MANAGER_ID LAST_NAME SALARY L_CSUM
    100 Mourgos 5800 5800
    100 Vollman 6500 12300
    100 Kaufling 7900 20200
    100 Weiss 8000 28200
    100 Fripp 8200 36400
    100 Zlotkey 10500 46900
    100 Raphaely 11000 68900
    100 Cambrault 11000 68900
    100 Errazuriz 12000 80900
    149 Taylor 8600 30200
    149 Hutton 8800 39000
    149 Abel 11000 50000
    201 Fay 6000 6000
    205 Gietz 8300 8300
    King 24000 24000
    For clear understanding read the following point:
    Whenever the order_by_clause results in identical
    values for multiple rows, the function returns the same result for
    each of those rows
    ITS THE CUMULATIVE SUM HERE.
    SO,IF TRY GIVING SAME NAME FOR ALL EMPLOYESS AND see the same result as you were getting with (partition by dept).
    so , sum function which u are using here is analytic function and so results in cumulative sum. and when identical values are identified, same result is displayed.
    Hope you got it!
    Cheers,
    Kishore KVR

  • Group By -- Having Clause related doubt.

    Hello,
    Can we Write/Use rather a 'Having Condition' Before a Group by Clause ..?
    If Yes then How does it Work.. I mean a 'Having' is a WHERE clause (filter) on Aggregate results ...
    SO how does Having works before grouping the Results..??

    Hi,
    Aijaz Mallick wrote:
    Hello,
    Can we Write/Use rather a 'Having Condition' Before a Group by Clause ..?What happens when you try it?
    If Yes then How does it Work.. I mean a 'Having' is a WHERE clause (filter) on Aggregate results ... Right; the HAVING clause is like another WHERE clause.
    The WHERE clause is applied before the GROUP BY is done, and the aggregate functions are computed.
    The HAVING clause is applied after the GROUP BY is done, and the aggregate functions are computed, so you can use aggregate functions in the HAVING clause.
    SO how does Having works before grouping the Results..??The order in which clauses appear in your code isn't necessarily the order in which they are performed. For example,
    SELECT    job
    ,         COUNT (*)  AS cnt
    FROM      scott.emp
    GROUP BY  job;Does it confuse you that this query can reference COUNT (*) in the SLECT clause, which is before the GROUP BY clause?
    The SELECT clause which always comes before the GROUP BY clause in code. That does not mean that the SELECT clause is completed before the GROUP BY clause is begun.
    If the documentation says that clauses must be in a certain order, then use that order, even if your current version of Oracle allows them to be in a different order. There's no guarantee that the next version of Oracle will allow something that was always said to be wrong.

  • Doubts on Program Groups

    Hi All,
    Program Groups has different meaning in ABAP.Could any body help me know the exact information on this... How the common data part will working according to this...
    Thank you...

    check this out
    link: [http://help.sap.com/saphelp_46c/helpdata/en/e4/2adbd7449911d1949c0000e8353423/content.htm]
    reward if helpful
    raam

  • Doubt regarding Grouping of Months

    Hello,
    Can i get any idea or any solution for grouping according to months.... <i.e> The output should appear like
    Jan --- Some calculation --- etc --- etc
    Feb --- Some calculation --- etc --- etc
    Mar --- Some calculation --- etc --- etc
    April --- Some calculation --- etc --- etc
    May --- Some calculation --- etc --- etc
    June --- Some calculation --- etc --- etc

    Hi,
    It depends if you want to group months from several years, or months within a year.
    Using the following sample data :with s as (
    select to_date('2009/01/13','yyyy/mm/dd') dt, 10 val from dual
    union all select to_date('2009/01/19','yyyy/mm/dd') dt, 15 val from dual
    union all select to_date('2009/02/09','yyyy/mm/dd') dt, 15 val from dual
    union all select to_date('2009/02/24','yyyy/mm/dd') dt, 20 val from dual
    union all select to_date('2010/01/11','yyyy/mm/dd') dt, 25 val from dual
    union all select to_date('2010/01/17','yyyy/mm/dd') dt, 30 val from dual
    union all select to_date('2010/02/10','yyyy/mm/dd') dt, 35 val from dual
    union all select to_date('2010/02/21','yyyy/mm/dd') dt, 40 val from dual
    select * from s;To group months within their respective year you can :SQL> with s as (
      2  select to_date('2009/01/13','yyyy/mm/dd') dt, 10 val from dual
      3  union all select to_date('2009/01/19','yyyy/mm/dd') dt, 15 val from dual
      4  union all select to_date('2009/02/09','yyyy/mm/dd') dt, 15 val from dual
      5  union all select to_date('2009/02/24','yyyy/mm/dd') dt, 20 val from dual
      6  union all select to_date('2010/01/11','yyyy/mm/dd') dt, 25 val from dual
      7  union all select to_date('2010/01/17','yyyy/mm/dd') dt, 30 val from dual
      8  union all select to_date('2010/02/10','yyyy/mm/dd') dt, 35 val from dual
      9  union all select to_date('2010/02/21','yyyy/mm/dd') dt, 40 val from dual
    10  )
    11  select to_char(trunc(dt,'month'),'Mon') month, sum(val) sval
    12  from s
    13  group by trunc(dt,'month')
    14  order by trunc(dt,'month') ;
    MON       SVAL
    Jan         25
    Feb         35
    Jan         55
    Feb         75Or you want to group months from several years, you can :SQL> with s as (
      2  select to_date('2009/01/13','yyyy/mm/dd') dt, 10 val from dual
      3  union all select to_date('2009/01/19','yyyy/mm/dd') dt, 15 val from dual
      4  union all select to_date('2009/02/09','yyyy/mm/dd') dt, 15 val from dual
      5  union all select to_date('2009/02/24','yyyy/mm/dd') dt, 20 val from dual
      6  union all select to_date('2010/01/11','yyyy/mm/dd') dt, 25 val from dual
      7  union all select to_date('2010/01/17','yyyy/mm/dd') dt, 30 val from dual
      8  union all select to_date('2010/02/10','yyyy/mm/dd') dt, 35 val from dual
      9  union all select to_date('2010/02/21','yyyy/mm/dd') dt, 40 val from dual
    10  )
    11  select to_char(dt,'Mon') Month, sum(val) sval
    12  from s
    13  group by to_char(dt,'Mon')
    14  order by to_number(to_char(to_date(to_char(dt,'Mon'),'Mon'),'mm')) ;
    MON       SVAL
    Jan         80
    Feb        110

  • Doubt Regarding status group with respect to Incompletion log

    Hi,
    I just want to know if in status group if i click the radio button delivery & billing then will it alllow me to create delivery and billing even if sales order is incomplete .

    Hi,
    No delivery & Billing are not carried out unless the sales order is complete. Selecting the  radiobuttons delivery & billing indicate that some input data is missing.
    Example Shipping point data in sales order is missing then delivery cannot be carried out and the system displays it in incompletion log.
    If payment terms are missing in sales order, then billing cannot be carried out and the system displays it in incompletion log.
    chan
    Message was edited by:
            hari sri

  • OTL (Oracle Time and Labor) Doubt on Timekeeper Groups API

    Hi,
    Using HXC TimeStore API we can Create/insert/update/delete TimeCards.
    Then what is the use of Timekeeper Groups API's HXC_TIMEKEEPER_GROUP_API ?
    Thanks.

    I see below two calls in the package body, what is meant by 'User Hook'?User hooks provide the client with the ability to add logic to application processing and to disable optional product processing. These User Hooks take the form of procedures that may be called by the application, in sequence, when the application takes a specified action on a specified object type -- http://orclpps.blogspot.ca/2008/01/user-hooks-in-oracle.html
    User Hooks are an easier way of extending the standard functionality of many Oracle Application modules. They are synonymous to database triggers, but are implemented as APIs (package.procedure). -- http://oraclewithbiju.blogspot.ca/2012/06/oracle-applications-user-hooks.html
    http://www.oracle.com/pls/ebs121/search?word=%27User+Hook%27&format=ranked&remark=quick_search
    https://forums.oracle.com/forums/search.jspa?threadID=&q=User+AND+Hooks&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    Thanks,
    Hussein

  • Doubts in VPN groups

    Hi Guys,
    Is it possible to define a single user in a two separate  VPN Group? If  yes, if the  user is connecting, which group will take into effect?
    PS:  Acc to my  knowledge, u can add many users to one group, the users will  have access  and permission depending upon the group he is in. Please  correct me if I  am wrong.

    Hi rizwan,
                     Thanks for the reply. Consider this example.
    username is: Adam. I am adding this user in two VPN groups namely, VPN1 and VPN2.
    For VPN1 group, I have set permission to admin level(for eg).
    For VPN2 group, I have set permission to operator level(for eg).
    1)So, when he login with his username, which group he will be into?
    2)So It is possible to have one user in two groups, right?
    PS:The user doesn't know the group he is added to, he will just type his username
    Regards,
    M.Viswesh

  • Largest and 2nd largest number query group by clause doubt

    Hi, I have the following data in the database
    deal id reporting date
    12 6/1/2012
    12 4/1/2012
    12 2/1/2012
    13 3/1/2012
    13 2/1/2012
    13 1/1/2012
    I want for each deal id , the highest reporitng date and the 2nd highest reporting date...
    i.e output
    deal id date1 date2
    12 6/1/2012 4/1/2012
    13 3/1/2012 2/1/2012
    I wrote the following query
    select dealID,reportingDate from XYZ ,(select deal id , max(reportingDate)as d1 from XYZ) B
    where
    dealId=b.dealID
    and reportingDate!=b.d1
    order by reportingDate desc
    the problem is it gets all reporting date but the highest one for each deal ID. I do not want all the dates to come. just the highest and second highest
    plz help
    Edited by: user7963410 on Sep 14, 2012 10:01 PM

    Venkadesh wrote:
    this ?This is one overcomplicated piece of code. And it is incorrect. First of all '6/1/2012' is a string, not a date, so ordering by it will produce incorrect results. For example (I assume '6/1/2012' is Januray 6, 2012), '6/1/2012' > '1/5/2012':
    SQL> with t(id,reporting) as
      2  (
      3  select 12,'6/1/2012' from dual
      4  union all
      5  select 12,'4/1/2012' from dual
      6  union all
      7  select 12,'1/5/2012' from dual
      8  union all
      9  select 13,'3/1/2012' from dual
    10  union all
    11  select 13,'2/1/2012' from dual
    12  union all
    13  select 13,'1/1/2012' from dual
    14  )
    15  select id,regexp_substr(reporting,'\d+.\d+.\d+') date1,
    16  regexp_substr(reporting,'\d+.\d+.\d+',1,2) date2
    17  from (select id,listagg(reporting,' ') within group(order by reporting desc)
    18   reporting from (select id,reporting
    19   from (select id,reporting,row_number() over(partition by id order by reporting desc) rn
    20  from t)
    21  where rn<=2)
    22  group by id)
    23  /
            ID DATE1           DATE2
            12 6/1/2012        4/1/2012
            13 3/1/2012        2/1/2012
    SQL> And code doesn't take into account id,reporting might have duplicates:
    SQL> with t(id,reporting) as
      2  (
      3  select 12,'6/1/2012' from dual
      4  union all
      5  select 12,'6/1/2012' from dual
      6  union all
      7  select 12,'4/1/2012' from dual
      8  union all
      9  select 12,'2/1/2012' from dual
    10  union all
    11  select 13,'3/1/2012' from dual
    12  union all
    13  select 13,'2/1/2012' from dual
    14  union all
    15  select 13,'1/1/2012' from dual
    16  )
    17  select id,regexp_substr(reporting,'\d+.\d+.\d+') date1,
    18  regexp_substr(reporting,'\d+.\d+.\d+',1,2) date2
    19  from (select id,listagg(reporting,' ') within group(order by reporting desc)
    20   reporting from (select id,reporting
    21   from (select id,reporting,row_number() over(partition by id order by reporting desc) rn
    22  from t)
    23  where rn<=2)
    24  group by id)
    25  /
            ID DATE1           DATE2
            12 6/1/2012        6/1/2012
            13 3/1/2012        2/1/2012
    SQL> Anyway, all we need is row_number and max:
    select  id,
            reporting date1,
            prev_reporting date2
      from  (
             select  id,
                     reporting,
                     row_number() over(partition by id order by reporting desc) rn,
                     max(reporting) over(partition by id order by reporting range between unbounded preceding and 1/24/60/60 preceding) prev_reporting
               from  t
      where rn = 1
    /For example:
    with t(id,reporting) as
    select 12,to_date('6/1/2012','dd/mm/yyyy') from dual
    union all
    select 12,to_date('6/1/2012','dd/mm/yyyy') from dual
    union all
    select 12,to_date('4/1/2012','dd/mm/yyyy') from dual
    union all
    select 12,to_date('2/1/2012','dd/mm/yyyy') from dual
    union all
    select 13,to_date('3/1/2012','dd/mm/yyyy') from dual
    union all
    select 13,to_date('2/1/2012','dd/mm/yyyy') from dual
    union all
    select 13,to_date('1/1/2012','dd/mm/yyyy') from dual
    select  id,
            reporting date1,
            prev_reporting date2
      from  (
             select  id,
                     reporting,
                     row_number() over(partition by id order by reporting desc) rn,
                     max(reporting) over(partition by id order by reporting range between unbounded preceding and 1/24/60/60 preceding) prev_reporting
               from  t
      where rn = 1
            ID DATE1           DATE2
            12 06-JAN-12       04-JAN-12
            13 03-JAN-12       02-JAN-12
    SQL> But I prefer:
    select  id,
            reporting date1,
            Nth_highest_reporting date2
      from  (
             select  id,
                     reporting,
                     row_number() over(partition by id order by reporting desc) rn,
                     lead(reporting,:n - 1) over(partition by id order by reporting desc) Nth_highest_reporting
               from  (
                      select  distinct *
                        from  t
      where rn = 1
    /Where :n is Nth highest. For example:
    SQL> variable n number
    SQL> exec :n := 2;
    PL/SQL procedure successfully completed.
    SQL> with t(id,reporting) as
      2  (
      3  select 12,to_date('6/1/2012','dd/mm/yyyy') from dual
      4  union all
      5  select 12,to_date('6/1/2012','dd/mm/yyyy') from dual
      6  union all
      7  select 12,to_date('4/1/2012','dd/mm/yyyy') from dual
      8  union all
      9  select 12,to_date('2/1/2012','dd/mm/yyyy') from dual
    10  union all
    11  select 12,to_date('1/1/2012','dd/mm/yyyy') from dual
    12  union all
    13  select 13,to_date('3/1/2012','dd/mm/yyyy') from dual
    14  union all
    15  select 13,to_date('2/1/2012','dd/mm/yyyy') from dual
    16  union all
    17  select 13,to_date('1/1/2012','dd/mm/yyyy') from dual
    18  )
    19  select  id,
    20          reporting date1,
    21          Nth_highest_reporting date2
    22    from  (
    23           select  id,
    24                   reporting,
    25                   row_number() over(partition by id order by reporting desc) rn,
    26                   lead(reporting,:n - 1) over(partition by id order by reporting desc) Nth_highest_reporting
    27             from  (
    28                    select  distinct *
    29                      from  t
    30                   )
    31          )
    32    where rn = 1
    33  /
            ID DATE1           DATE2
            12 06-JAN-12       04-JAN-12
            13 03-JAN-12       02-JAN-12
    SQL> exec :n := 3;
    PL/SQL procedure successfully completed.
    SQL> /
            ID DATE1           DATE2
            12 06-JAN-12       02-JAN-12
            13 03-JAN-12       01-JAN-12
    SQL> exec :n := 4;
    PL/SQL procedure successfully completed.
    SQL> /
            ID DATE1           DATE2
            12 06-JAN-12       01-JAN-12
            13 03-JAN-12
    SQL> SY.

Maybe you are looking for

  • Need Suggestion On Real Time Data Accees

    Hi, Our application (let say A) runs on * 8.1.7.4.0* Another Application (let say B) runs on *10.2.0.4.0* Both the application A and B exchange data through DB links. Both the application A and B perform select and DML on other tables. Application A

  • I suspect drivers are the culprit

    HP Envy laptop  When using hdmi and connecting to my tv, the audio stutters often, especially while watching videos. My other issue is my when I'm connected to my wifi, it randomly stops working, I have to disconnect and reconnect, sometimes every 20

  • Tax and Salesman Object?

    Hey all, i want to update all the tax and salesmen entries over the SAP object. Which object should i use for the tax groups and the Salespersons, because over the SAPbobsCOM i cannot use the SalesPersons object. Thanks:) Maggie

  • My PC Froze While My iPod Was Saying "Do Not Disconnect"

    My computer is frozen and my iPod is connected to it and saying "Do Not Discount" but my iPod is not frozen. Do I unplug my iPod or shut down the computer? What do I do?

  • Transcation for table maintenance

    Hi All, Is it possible to create a transaction for table maintenace of a table ? I mean, if the transaction is run, the table maintenance screen for my table should appear. (instead of going through SM30). If this is possible how do i do it ? Thank y