Help in Total sum query

Hello, How I can sum(code1). Every code1 has a group and every group's total (total_per) should be 100. I want to add the comments column in the result as well. Thanks.
create table #Cumulate (code numeric (10), code1 numeric (10), total_per numeric(10),code_desc char(20))
insert into #Cumulate values (1,121,10,'DHJ')
insert into #Cumulate values (2,121,90,'DHJ')
insert into #Cumulate values (3,121,10,'DHJ')
insert into #Cumulate values (4,122,10,'CRT')
insert into #Cumulate values (5,122,80,'CRT')
insert into #Cumulate values (6,122,05,'CRT')
insert into #Cumulate values (7,122,10,'CRT')
insert into #Cumulate values (8,123,10,'DRT')
insert into #Cumulate values (9,123,60,'DRT')
insert into #Cumulate values (10,123,10,'DRT')
insert into #Cumulate values (11,123,10,'DRT')
insert into #Cumulate values (12,123,10,'DRT')
insert into #Cumulate values (13,124,20,'DRT')
insert into #Cumulate values (14,124,60,'DRT')
insert into #Cumulate values (15,124,10,'DRT')
insert into #Cumulate values (16,124,10,'DRT')
insert into #Cumulate values (17,124,10,'DRT')
--Results
Code1 total_per Commments
121   100         Total is 100
122   105         Total is not 100
123   100         Total is 100
124   110        Total is not 100

Try the below:
Select Code1, Sum(Total_per) total_per, 'Total is '+Case when Sum(Total_per)=100 then '' else ' not' end+'100' Comments
From
#Cumulate
Group by Code1
However, I would suggest you to do the comment session at presentation layer, which would be a good for performance.
Please mark this reply as answer if it solved your issue or vote as helpful if it helped.
 [Blog]

Similar Messages

  • Sum Total in Query Print Layout

    Hi, all
    I have a report which is created by a query, How can I insert a variable to show the Total Sum in footer.
    Thanks
    kimmy

    Hai!
    see this thread.
    Sub totals in PLD
    regards,
    Thanga Raj.K

  • Help in correcting the query

    Hi,
    I have below query:
    select u.v_um_code,v_um_name,count(f.v_fc_code), count(s.n_sl_no), count(distinct s.n_agent_no)
    from subm_buss_um_master u,subm_buss_fc_master f,submitted_business_raw s
    where u.v_um_code=f.v_um_code and f.v_fc_code=s.n_agent_no
    and f.v_status='A' and u.v_status='A'
    and trunc(d_submitted) between '01-JUL-2004' AND '31-JUL-2004'
    group by u.v_um_code,v_um_name;
    the output should be such that first all the records should be fetched from subm_buss_um_master table (where u.v_status='A')--> then count(f.v_fc_code) then -->count(s.n_sl_no), count(distinct s.n_agent_no)
    the data/columns in these tables is large, I cannot paste here.
    Thanks in advance
    Tariq.

    Hi,
    If SET operator UNION helps then great!!!
    For example: As per my requirement, first all employees and sum of salary.....is the query.
    SELECT ename, sal FROM emp
    UNION
    SELECT 'Grand Total ', SUM(sal) FROM emp
    ORDER BY sal;
    Regards,
    Sailaja

  • Compute totals in query

    Hi,
    I can not compute the t.quantity and t.linetotals in this query.
    SELECT T.ItemCode,  T.dscription, SUM(T.quantity) as HVH, sum(T.linetotal) as Omzet
    FROM
    (select
    itemcode, dscription, quantity, linetotal
    from
    inv1 t0 inner join oinv t1 on t0.docentry = t1.docentry
    where
    t1.cardcode between '300000' and '310000' and
    t1.docdate >= '20101101' and t1.docdate <= '20101130'
    and t0.itemcode in (select itemcode from oitm t2 where t2.cardcode = '600319')
    UNION ALL
    select
    itemcode, dscription, -quantity as quantity, -linetotal as linetotal
    from
    rin1 t0 inner join orin t1 on t0.docentry = t1.docentry
    where
    t1.cardcode between '300000' and '310000' and
    t1.docdate >= '20101101' and t1.docdate <= '20101130'
    and t0.itemcode in (select itemcode from oitm t2 where t2.cardcode = '600319')) T
    group by T.itemcode, T.dscription
    order by T.itemcode
    Is there somebody who can help??
    thx
    mark

    Hi Mark,
    did not Gordon answer your issue allready in this thread ? See totals in query on 1 line
    Thats the same query, isn't it?
    Regards Steffen

  • Need help on oracle sql query

    Hi team,
    Please help me on below query,
    I have table like given below
    Tran_Id  tran_date   amount. Actorid
       1.         10-apr-15.   100.         1
       2.         11-apr-15.   100.         1
       3.         11-apr-15.   900.         1
       4.         12-apr-15.   100.         1
       5.         13-apr-15.   350.         1
       6.         14-apr-15.   400.         1
    Now please find the query,
    I want all the actor ids whos tran amount
    >1500 and the  date when the tran amount
    Has breached
    Ex:
    Actor-id.  Breached-date.    Total
      1.              13-apr-15.            1900
    How can I write a query for above requirement?
    Regards,
    Rajendra

    Your solution (same as Saubhik's) is incorrect. Look at source data - multiple transactions can occur same day. Therefore, your qury will return wrong results if breached amount is 1000:
    with trans as (
    select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
    select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
    select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
    select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
    select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    trans_running_tot as (
    select tran_id, tran_date,
      sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
    from trans
    trans_ranked as (
    select actorid,tran_id, tran_date,
      rank() over (partition by actorid order by tot_amt) rk
    from trans_running_tot
    where tot_amt > 1000
    select * from trans_ranked where rk=1
       ACTORID    TRAN_ID TRAN_DATE         RK
             1          2 11-APR-15          1 -- here total amount was only 200
             1          3 11-APR-15          1
             2          8 13-APR-15          1
    SQL>
    As you can see, 2 rows were returned for actor 1. Why? Default for analytic ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Therefore, all rows with same transation_date will fall into same window:
    SQL>  with trans as (
      2   select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
      3   select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
      4   select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
      5   select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
      6   select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
      7   select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
      8   select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
      9   select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    10   select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    11   select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    12   )
    13  select tran_id, tran_date,
    14    sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
    15  from trans
    16  /
       TRAN_ID TRAN_DATE    TOT_AMT    ACTORID
             1 10-APR-15        100          1
             2 11-APR-15       1100          1
             3 11-APR-15       1100          1
             4 12-APR-15       1200          1
             5 13-APR-15       1550          1
             6 14-APR-15       1950          1
             7 12-APR-15        300          2
             8 13-APR-15       1500          2
             9 14-APR-15       1800          2
            10 15-APR-15       2100          2
    10 rows selected.
    SQL>
    So correct solution is to ORDER BY transation id. Also, just in case if amount can be 0, we should add tranaction id when ordering by sum:
    with trans as (
    select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
    select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
    select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
    select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
    select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    trans_running_tot as (
    select tran_id, tran_date,
      sum(amount) over (partition by actorid order by tran_id) tot_amt, actorid
    from trans
    trans_ranked as (
    select actorid,tran_id, tran_date,
      rank() over (partition by actorid order by tot_amt,tran_id) rk
    from trans_running_tot
    where tot_amt > 1000
    select * from trans_ranked where rk=1
       ACTORID    TRAN_ID TRAN_DATE         RK
             1          3 11-APR-15          1
             2          8 13-APR-15          1
    SQL>
    SY.

  • Help needed regarding SUM keyword in an ITAB loop

    Hello,
    I am maintaining a code as given below.
    LOOP AT itab INTO totwa.
    SUM.
    ENDLOOP.
    totwa is defined as a workarea which is needed to hold the sum totals of the fields in the itab. According to the documentation of SUM, it should calculate the sum totals and should put the totals in the workarea mentioned. But somehow its not calculating the value. Could anyone please help me in resolving this issue. Please guide me with your thoughts as to what might have gone wrong.
    Note: the itab fields are of type P.
    Thanks in advance
    Sudha Naik

    Hello Suha
    According to the ABAP documentation the SUM statement is used in a specific situation:
    <b>Syntax
    SUM. </b>
    <b>Effect </b>
    <i>The statement SUM can only be specified within a loop starting with LOOP, and is only considered within a AT-ENDAT control structure. Prerequisites for using the statement SUM include using the addition INTO in the LOOP statement, and that the specified work area wa is compatible with the row type of the internal table. In addition, SUM cannot be used when the row type of the internal table itab contains components that are tables. </i>
    <i>The statement SUM calculates the component total with the numeric data type ( i, p, f) of all rows in the current control level and assigns these to the components of the work area wa. In the control levels FIRST, LAST , and outside of an AT-ENDAT control structure, the system calculates the sum of numeric components of all rows in the internal table.</i>
    I hope the following sample report will clarify the use of <b>SUM </b>and <b>COLLECT</b>.
    *& Report  ZUS_SDN_COLLECT
    REPORT  zus_sdn_collect.
    TYPES: BEGIN OF ty_s_line.
    TYPES:   key(1)    TYPE n.
    TYPES:   value     TYPE p DECIMALS 2.
    TYPES: END OF ty_s_line.
    TYPES: ty_t_itab    TYPE STANDARD TABLE OF ty_s_line
                        WITH DEFAULT KEY.
    DATA:
      gs_line       TYPE ty_s_line,
      gt_itab       TYPE ty_t_itab,
      gt_itab_coll  TYPE ty_t_itab.
    START-OF-SELECTION.
      DO 3 TIMES.
        gs_line-key = syst-index.
        gs_line-value = syst-index * '2.3'.
        APPEND gs_line TO gt_itab.
        APPEND gs_line TO gt_itab.
      ENDDO.
      gs_line-key = 4.
      gs_line-value = '5.5'.
      APPEND gs_line TO gt_itab.
      WRITE: / 'Initial list'.
      LOOP AT gt_itab INTO gs_line.
        WRITE: / gs_line-key,
                 gs_line-value.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
      WRITE: / 'Using SUM statement with AT END OF'.
      SORT gt_itab BY key.
      LOOP AT gt_itab INTO gs_line.
        AT END OF key.
          SUM.
          WRITE: / gs_line-key,
                   gs_line-value.
        ENDAT.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
      WRITE: / 'Using SUM statement without control structure (1)'.
      SORT gt_itab BY key.
      LOOP AT gt_itab INTO gs_line.
        SUM.
        WRITE: / gs_line-key,
                 gs_line-value.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
      WRITE: / 'Using SUM statement without control structure (2)'.
      SORT gt_itab BY key.
      LOOP AT gt_itab INTO gs_line.
        SUM.
        WRITE: / gs_line-key,
                 gs_line-value.
        EXIT.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
      WRITE: / 'Using COLLECT statement'.
      REFRESH: gt_itab_coll.
      LOOP AT gt_itab INTO gs_line.
        COLLECT gs_line INTO gt_itab_coll.
      ENDLOOP.
      LOOP AT gt_itab_coll INTO gs_line.
        WRITE: / gs_line-key,
                 gs_line-value.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
      WRITE: / 'Using COLLECT statement for total sum'.
      REFRESH: gt_itab_coll.
      LOOP AT gt_itab INTO gs_line.
        gs_line-key = 0.
        COLLECT gs_line INTO gt_itab_coll.
      ENDLOOP.
      LOOP AT gt_itab_coll INTO gs_line.
        WRITE: / gs_line-key,
                 gs_line-value.
      ENDLOOP.
      WRITE: / syst-uline.
      SKIP 2.
    END-OF-SELECTION.
    Regards
      Uwe

  • How to Hide rows in ALV without affecting total sum at the end of table?

    Hi,
    I need some help in hiding particular rows in an ALV Grid without affecting the total sum at the end of the table. I am trying to hide the rows that have negative quantities, but I still need those values so that the user can still compute for the total sums. Can anyone help? Thanks.
    Joseph

    Hi,
    Hopw this way you can hide the rows in the GRID.
    DATA:
      ld_column      TYPE lvc_fname,
      ld_hide          TYPE abap_bool.
    FIELD-SYMBOLS:
      <ls_entry>     TYPE any,
      <ld_fld>         TYPE any.
      ld_column = 'COL_1'.  " column which you want to suppress if everything is zero
      ld_hide     = abap_true.  " = 'X';  default hide column
      LOOP at <gt_outtab> ASSIGNING <ls_entry>.
        ASSIGN COMPONENT (ld_column) OF STRUCTURE <ls_entry> TO <ld_fld>.
        IF ( <ld_fld>   > 0 ).
          ld_hide = abap_false.  " display column because at least single value > 0
          EXIT.  " leave LOOP
        ENDIF.
      ENDLOOP.
      READ TABLE gt_fcat INTO ls_fcat
                           WITH KEY fieldname = ld_column.
      IF ( syst-subrc = 0 ).
        ls_fcat-no_out = ld_hide.
        MODIFY gt_fcat FROM ls_fcat INDEX syst-tabix.
      ENDIF.
    hop you will get the total with for those columns too.
    Regards,
    Madhavi

  • Help tune this monster query please

    Hi, I have a query that runs for a long time. Its a system generated query but I need to improve its performance. I have enough indexes on the tables. Here is the query, its explain plan and the tkprof:
    The QUERY
    SELECT FD.FORM_ID, FD.FIELD_NAME, FD.FIELD_TEXT, FD.OPTION_TEXT, FD.OPTION_TYPE, FD.FIELD_ORDER, FD.LIST_ORDER,
    FD.MULTIPLE_ANSWER, FD.FIELD_INSTANCE, NVL(AD.APPS,0) APPS
    FROM (
        SELECT FIELD_NAME, FIELD_VALUE, INSTANCE, COUNT(0) APPS
        FROM APPLICATION_DATA AD
        WHERE APPLICATION_ID IN (
            SELECT A.APPLICATION_ID
            FROM APPLICATIONS A
            WHERE A.DELETED = 0 AND DECODE(A.TRAY,'Incomplete','Incomplete','Complete') = 'Complete' AND A.JOB_ID IN (
                SELECT JOB_ID
                FROM JOBS J
                WHERE J.ACCOUNT_ID IN (
                    SELECT ACCOUNT_ID
                        FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = J.ACCOUNT_ID ) )                  AND A.ACCOUNT_ID IN (
                        SELECT ACCOUNT_ID
                        FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = 113346 ) AND                       FIELD_NAME IN (
                            SELECT FIELD_NAME FROM APPLICATION_FIELDS
                                WHERE FIELD_TYPE IN ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara') ) )
        GROUP BY FIELD_NAME, FIELD_VALUE, INSTANCE ) AD, (
            SELECT AF.FORM_ID, AF.FIELD_NAME, AF.FIELD_TEXT, AFO.OPTION_TEXT, AFO.OPTION_TYPE, AF.FIELD_ORDER, AFO.LIST_ORDER,
            DECODE(AF.FIELD_TYPE,'Checkbox',1,'SelectM',1,0) MULTIPLE_ANSWER, AF.FIELD_INSTANCE
            FROM APPLICATION_FIELDS AF, APPLICATION_FIELD_OPTIONS AFO, JOB_FORMS JF
            WHERE AFO.FIELD_NAME = AF.FIELD_NAME AND AFO.FORM_ID = AF.FORM_ID AND JF.FORM_ID = AF.FORM_ID AND AF.FIELD_TYPE IN
            ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara') AND JF.JOB_ID IN (
                SELECT JOB_ID
                FROM JOBS J
                WHERE J.ACCOUNT_ID IN (
                    SELECT ACCOUNT_ID
                    FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = 113346 ) ) ) FD
    WHERE AD.FIELD_NAME = FD.FIELD_NAME AND AD.FIELD_VALUE = FD.OPTION_TEXT AND AD.INSTANCE = FD.FIELD_INSTANCE
    GROUP BY FD.FORM_ID, FD.FIELD_NAME, FD.FIELD_TEXT, FD.OPTION_TEXT, FD.OPTION_TYPE, FD.FIELD_ORDER, FD.LIST_ORDER,
    FD.MULTIPLE_ANSWER, FD.FIELD_INSTANCE, NVL(AD.APPS,0)
    ORDER BY FD.FORM_ID ASC, FD.FIELD_ORDER ASCEXPLAIN PLAN OUTPUT
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    Plan hash value: 3519364953                                                                                                                                                                            
    | Id  | Operation                                   | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |                                                                             
    |   0 | SELECT STATEMENT                            |                            |     1 |   120 |   763   (2)| 00:00:10 |                                                                             
    |   1 |  SORT GROUP BY                              |                            |     1 |   120 |   763   (2)| 00:00:10 |                                                                             
    |   2 |   VIEW                                      |                            |     1 |   120 |   762   (1)| 00:00:10 |                                                                             
    |   3 |    HASH GROUP BY                            |                            |     1 |   220 |   762   (1)| 00:00:10 |                                                                             
    |*  4 |     FILTER                                  |                            |       |       |            |          |                                                                             
    |*  5 |      TABLE ACCESS BY INDEX ROWID            | APPLICATION_DATA           |     1 |    45 |     6   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |   6 |       NESTED LOOPS                          |                            |    40 |  8800 |   486   (2)| 00:00:06 |                                                                             
    |*  7 |        HASH JOIN                            |                            |    60 | 10500 |   125   (4)| 00:00:02 |                                                                             
    |*  8 |         HASH JOIN                           |                            |    60 |  7320 |    53   (6)| 00:00:01 |                                                                             
    |   9 |          NESTED LOOPS                       |                            |    11 |   297 |     9  (12)| 00:00:01 |                                                                             
    |  10 |           VIEW                              | VW_NSO_3                   |     3 |    15 |     5   (0)| 00:00:01 |                                                                             
    |  11 |            HASH UNIQUE                      |                            |     3 |    69 |            |          |                                                                             
    |  12 |             TABLE ACCESS BY INDEX ROWID     | JOBS                       |     3 |    30 |     3   (0)| 00:00:01 |                                                                             
    |  13 |              NESTED LOOPS                   |                            |     3 |    69 |     5   (0)| 00:00:01 |                                                                             
    |  14 |               VIEW                          | VW_NSO_1                   |     1 |    13 |     2   (0)| 00:00:01 |                                                                             
    |* 15 |                CONNECT BY WITH FILTERING    |                            |       |       |            |          |                                                                             
    |  16 |                 TABLE ACCESS BY INDEX ROWID | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 17 |                  INDEX UNIQUE SCAN          | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  18 |                 NESTED LOOPS                |                            |       |       |            |          |                                                                             
    |  19 |                  BUFFER SORT                |                            |       |       |            |          |                                                                             
    |  20 |                   CONNECT BY PUMP           |                            |       |       |            |          |                                                                             
    |  21 |                  TABLE ACCESS BY INDEX ROWID| AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 22 |                   INDEX UNIQUE SCAN         | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 23 |                 TABLE ACCESS FULL           | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 24 |               INDEX RANGE SCAN              | JOBS_ACCOUNT_ID            |     3 |       |     1   (0)| 00:00:01 |                                                                             
    |* 25 |           INDEX RANGE SCAN                  | JOBS_FORMS_JID_FID         |     4 |    88 |     1   (0)| 00:00:01 |                                                                             
    |* 26 |          TABLE ACCESS FULL                  | APPLICATION_FIELDS         |  3579 |   332K|    43   (3)| 00:00:01 |                                                                             
    |  27 |         TABLE ACCESS FULL                   | APPLICATION_FIELD_OPTIONS  | 32897 |  1702K|    72   (3)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 28 |        INDEX RANGE SCAN                     | IDX$$_B8D40001             |     4 |       |     3   (0)| 00:00:01 |                                                                             
    |* 29 |      FILTER                                 |                            |       |       |            |          |                                                                             
    |  30 |       MERGE JOIN CARTESIAN                  |                            |     3 |   225 |    11   (0)| 00:00:01 |                                                                             
    |  31 |        NESTED LOOPS                         |                            |     1 |    53 |     6   (0)| 00:00:01 |                                                                             
    |  32 |         NESTED LOOPS                        |                            |     1 |    40 |     4   (0)| 00:00:01 |                                                                             
    |* 33 |          TABLE ACCESS BY INDEX ROWID        | APPLICATIONS               |     1 |    30 |     3   (0)| 00:00:01 |                                                                             
    |* 34 |           INDEX UNIQUE SCAN                 | APPS_APP_ID                |     1 |       |     2   (0)| 00:00:01 |                                                                             
    |  35 |          TABLE ACCESS BY INDEX ROWID        | JOBS                       | 18780 |   183K|     1   (0)| 00:00:01 |                                                                             
    |* 36 |           INDEX UNIQUE SCAN                 | JOBS_JOB_ID                |     1 |       |     0   (0)| 00:00:01 |                                                                             
    |* 37 |         VIEW                                | VW_NSO_2                   |     1 |    13 |     2   (0)| 00:00:01 |                                                                             
    |* 38 |          CONNECT BY WITH FILTERING          |                            |       |       |            |          |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |  39 |           TABLE ACCESS BY INDEX ROWID       | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    |* 40 |            INDEX UNIQUE SCAN                | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  41 |           NESTED LOOPS                      |                            |       |       |            |          |                                                                             
    |  42 |            BUFFER SORT                      |                            |       |       |            |          |                                                                             
    |  43 |             CONNECT BY PUMP                 |                            |       |       |            |          |                                                                             
    |  44 |            TABLE ACCESS BY INDEX ROWID      | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 45 |             INDEX UNIQUE SCAN               | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 46 |           TABLE ACCESS FULL                 | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |  47 |        BUFFER SORT                          |                            |     3 |    66 |     9   (0)| 00:00:01 |                                                                             
    |  48 |         INLIST ITERATOR                     |                            |       |       |            |          |                                                                             
    |* 49 |          INDEX RANGE SCAN                   | IDX$$_91CA0001             |     3 |    66 |     5   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 50 |       FILTER                                |                            |       |       |            |          |                                                                             
    |* 51 |        CONNECT BY WITH FILTERING            |                            |       |       |            |          |                                                                             
    |  52 |         TABLE ACCESS BY INDEX ROWID         | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    |* 53 |          INDEX UNIQUE SCAN                  | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  54 |         NESTED LOOPS                        |                            |       |       |            |          |                                                                             
    |  55 |          BUFFER SORT                        |                            |       |       |            |          |                                                                             
    |  56 |           CONNECT BY PUMP                   |                            |       |       |            |          |                                                                             
    |  57 |          TABLE ACCESS BY INDEX ROWID        | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 58 |           INDEX UNIQUE SCAN                 | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 59 |         TABLE ACCESS FULL                   | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    Predicate Information (identified by operation id):                                                                                                                                                    
       4 - filter( EXISTS (SELECT 0 FROM "APPLICATIONS" "A","JOBS" "SYS_ALIAS_1", (SELECT "ACCOUNT_ID" "$nso_col_1"                                                                                        
                  FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL) "VW_NSO_2","APPLICATION_FIELDS"                                                                                        
                  "APPLICATION_FIELDS" WHERE  EXISTS (SELECT 0 FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL AND                                                                        
                  ("ACCOUNT_ID"=:B1)) AND ("FIELD_TYPE"='Checkbox' OR "FIELD_TYPE"='Radio' OR "FIELD_TYPE"='RadioHoriz' OR                                                                                 
                  "FIELD_TYPE"='RadioPara' OR "FIELD_TYPE"='Select' OR "FIELD_TYPE"='SelectM') AND "FIELD_NAME"=:B2 AND                                                                                    
                  "A"."ACCOUNT_ID"="$nso_col_1" AND "A"."JOB_ID"="JOB_ID" AND "A"."APPLICATION_ID"=:B3 AND                                                                                                 
                  DECODE("A"."TRAY",'Incomplete','Incomplete','Complete')='Complete' AND "A"."DELETED"=0))                                                                                                 
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
       5 - filter("FIELD_NAME"="AF"."FIELD_NAME" AND "INSTANCE"="AF"."FIELD_INSTANCE")                                                                                                                     
       7 - access("AFO"."FIELD_NAME"="AF"."FIELD_NAME" AND "AFO"."FORM_ID"="AF"."FORM_ID")                                                                                                                 
       8 - access("JF"."FORM_ID"="AF"."FORM_ID")                                                                                                                                                           
      15 - filter("ACCOUNT_ID"=113346)                                                                                                                                                                     
      17 - access("ACCOUNT_ID"=113346)                                                                                                                                                                     
      22 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      23 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      24 - access("J"."ACCOUNT_ID"="$nso_col_1")                                                                                                                                                           
      25 - access("JF"."JOB_ID"="$nso_col_1")                                                                                                                                                              
      26 - filter("AF"."FIELD_TYPE"='Checkbox' OR "AF"."FIELD_TYPE"='Radio' OR "AF"."FIELD_TYPE"='RadioHoriz' OR                                                                                           
                  "AF"."FIELD_TYPE"='RadioPara' OR "AF"."FIELD_TYPE"='Select' OR "AF"."FIELD_TYPE"='SelectM')                                                                                              
    PLAN_TABLE_OUTPUT  FOR THE QUERY                                                                                                                                                                                    
      28 - access("FIELD_VALUE"="AFO"."OPTION_TEXT")                                                                                                                                                       
      29 - filter( EXISTS (SELECT 0 FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL AND                                                                                                   
                  ("ACCOUNT_ID"=:B1)))                                                                                                                                                                     
      33 - filter(DECODE("A"."TRAY",'Incomplete','Incomplete','Complete')='Complete' AND "A"."DELETED"=0)                                                                                                  
      34 - access("A"."APPLICATION_ID"=:B1)                                                                                                                                                                
      36 - access("A"."JOB_ID"="JOB_ID")                                                                                                                                                                   
      37 - filter("A"."ACCOUNT_ID"="$nso_col_1")                                                                                                                                                           
      38 - filter("ACCOUNT_ID"=113346)                                                                                                                                                                     
      40 - access("ACCOUNT_ID"=113346)                                                                                                                                                                     
      45 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      46 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
      49 - access("FIELD_NAME"=:B1 AND ("FIELD_TYPE"='Checkbox' OR "FIELD_TYPE"='Radio' OR "FIELD_TYPE"='RadioHoriz'                                                                                       
                  OR "FIELD_TYPE"='RadioPara' OR "FIELD_TYPE"='Select' OR "FIELD_TYPE"='SelectM'))                                                                                                         
      50 - filter("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      51 - filter("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      53 - access("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      58 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      59 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
    106 rows selected.TKPROF FOR THE QUERY
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.05       0.08          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch       17   1040.45    1018.36          0   48926569          0         229
    total       19   1040.50    1018.44          0   48926569          0         229
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 68
    Rows     Row Source Operation
        229  SORT GROUP BY (cr=48926569 pr=0 pw=0 time=1018362160 us)
        454   VIEW  (cr=48926569 pr=0 pw=0 time=1018361382 us)
        454    HASH GROUP BY (cr=48926569 pr=0 pw=0 time=1018360468 us)
    185302     FILTER  (cr=48926569 pr=0 pw=0 time=877249113 us)
    1440799      TABLE ACCESS BY INDEX ROWID APPLICATION_DATA (cr=11309333 pr=0 pw=0 time=213262026 us)
    82907114       NESTED LOOPS  (cr=174051 pr=0 pw=0 time=166906535 us)
       1790        HASH JOIN  (cr=625 pr=0 pw=0 time=41617 us)
        121         HASH JOIN  (cr=310 pr=0 pw=0 time=11263 us)
         39          NESTED LOOPS  (cr=121 pr=0 pw=0 time=6894 us)
         44           VIEW  VW_NSO_3 (cr=75 pr=0 pw=0 time=6424 us)
         44            HASH UNIQUE (cr=75 pr=0 pw=0 time=6333 us)
         44             TABLE ACCESS BY INDEX ROWID JOBS (cr=75 pr=0 pw=0 time=3090 us)
         52              NESTED LOOPS  (cr=32 pr=0 pw=0 time=58177 us)
          7               VIEW  VW_NSO_1 (cr=23 pr=0 pw=0 time=1242 us)
          7                CONNECT BY WITH FILTERING (cr=23 pr=0 pw=0 time=1212 us)
          1                 TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=3 pr=0 pw=0 time=185 us)
          1                  INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=2 pr=0 pw=0 time=100 us)(object id 60086)
          6                 NESTED LOOPS  (cr=20 pr=0 pw=0 time=590 us)
          7                  BUFFER SORT (cr=0 pr=0 pw=0 time=248 us)
          7                   CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=95 us)
          6                  TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=20 pr=0 pw=0 time=314 us)
          6                   INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=14 pr=0 pw=0 time=188 us)(object id 60086)
          0                 TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)
         44               INDEX RANGE SCAN JOBS_ACCOUNT_ID (cr=9 pr=0 pw=0 time=280 us)(object id 60253)
         39           INDEX RANGE SCAN JOBS_FORMS_JID_FID (cr=46 pr=0 pw=0 time=968 us)(object id 60299)
       3579          TABLE ACCESS FULL APPLICATION_FIELDS (cr=189 pr=0 pw=0 time=14469 us)
      32524         TABLE ACCESS FULL APPLICATION_FIELD_OPTIONS (cr=315 pr=0 pw=0 time=32629 us)
    82905323        INDEX RANGE SCAN IDX$$_B8D40001 (cr=173426 pr=0 pw=0 time=83870105 us)(object id 60121)
    185297      FILTER  (cr=37617236 pr=0 pw=0 time=749052070 us)
    185297       MERGE JOIN CARTESIAN (cr=37617196 pr=0 pw=0 time=742583363 us)
    185297        NESTED LOOPS  (cr=35393366 pr=0 pw=0 time=706772617 us)
    1139675         NESTED LOOPS  (cr=9180841 pr=0 pw=0 time=84949686 us)
    1140164          TABLE ACCESS BY INDEX ROWID APPLICATIONS (cr=5760834 pr=0 pw=0 time=46774108 us)
    1440060           INDEX UNIQUE SCAN APPS_APP_ID (cr=4320774 pr=0 pw=0 time=24380604 us)(object id 60107)
    1139675          TABLE ACCESS BY INDEX ROWID JOBS (cr=3420007 pr=0 pw=0 time=28126171 us)
    1139675           INDEX UNIQUE SCAN JOBS_JOB_ID (cr=2280328 pr=0 pw=0 time=14563524 us)(object id 60252)
    185297         VIEW  VW_NSO_2 (cr=26212525 pr=0 pw=0 time=613602445 us)
    6866175          CONNECT BY WITH FILTERING (cr=26212525 pr=0 pw=0 time=614183170 us)
    1139675           TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=3419025 pr=0 pw=0 time=24323520 us)
    1139675            INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=2279350 pr=0 pw=0 time=13905212 us)(object id 60086)
    6838050           NESTED LOOPS  (cr=22793500 pr=0 pw=0 time=388173853 us)
    7977725            BUFFER SORT (cr=0 pr=0 pw=0 time=178812411 us)
    7977725             CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=57522094 us)
    6838050            TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=22793500 pr=0 pw=0 time=179425469 us)
    6838050             INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=15955450 pr=0 pw=0 time=113988543 us)(object id 60086)
          0           TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)
    185297        BUFFER SORT (cr=2223830 pr=0 pw=0 time=24721936 us)
    1208625         INLIST ITERATOR  (cr=2223830 pr=0 pw=0 time=26470412 us)
    1208625          INDEX RANGE SCAN IDX$$_91CA0001 (cr=2223830 pr=0 pw=0 time=18174073 us)(object id 60129)
          2       FILTER  (cr=40 pr=0 pw=0 time=1292 us)
          2        CONNECT BY WITH FILTERING (cr=40 pr=0 pw=0 time=1276 us)
          2         TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=6 pr=0 pw=0 time=86 us)
          2          INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=4 pr=0 pw=0 time=46 us)(object id 60086)
         10         NESTED LOOPS  (cr=34 pr=0 pw=0 time=791 us)
         12          BUFFER SORT (cr=0 pr=0 pw=0 time=369 us)
         12           CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=127 us)
         10          TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=34 pr=0 pw=0 time=376 us)
         10           INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=24 pr=0 pw=0 time=242 us)(object id 60086)
          0         TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)Any help in tuning this query to run faster will be highly appreciated. I also noticed merge join certesian on the tkprof and explain plan. Any idea in takling that will also be appreciated.
    Cheers,
    Ade

    It's quite hard to tune a query without seeing the table structure and available indices as well as relationship between each other but I'll try.
    In your sql which you've given the table alias AD, you have this filter criteria
                  AND    FIELD_NAME IN (                        
                         SELECT FIELD_NAME
                         FROM   APPLICATION_FIELDS                            
                         WHERE  FIELD_TYPE IN ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara')
                         ) </br>
    My question is, is FIELD_NAME a column in the APPLICATION_DATA table? If it is, try moving this clause outside of the current sub-query it is in, i.e. one more level up. It looks like you put them inside the wrong level.
    I would also try converting this <COL> IN <SUB-QUERY> to a join, if that wouldn't affect the no. of rows returned. I can't tell for sure since I dont know the relationship between your tables.
    It looks to me like you're doing this
    SELECT <col list>
    FROM   ( SELECT                                         -- LEVEL 1
             FROM   APPLICATION_DATA AD
             WHERE  AD.APPLICAITON_ID IN (                  -- LEVEL 2
                    SELECT
                    FROM   APPLICATIONS A
                    WHERE  A.JOB_ID IN (
                           <SUBQUERY>
                    AND    A.ACCOUNT_ID IN (
                           <SUBQUERY>
                    AND FIELDNAME IN ( -- SHOULD BE INSIDE LEVEL1
    <SUBQUERY>
           ) AD,
           ( SELECT ....
           ) FD
    WHERE  ....

  • Help required for the query

    sir
    below query runs fine
    but the probblem is...i am not able to display the figures in the format '999999.99'
    Also please guide me as to make the query short... can i use cursors here?
    i am using 10g
    select
    LBRCODE branch,
    trim(substr(PRDACCTID,1,8)) product,
    sum(case when totsanclimit between 0 and 200000  then
         (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-1",
    SUM( CASE WHEN TOTSANCLIMIT between 0 and 200000 then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE
    0 end) AS"Bkt_1",
    sum(case when totsanclimit between 200001 and 1000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-2",
    SUM(
    CASE WHEN TOTSANCLIMIT between 200001 and 1000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_2",
    sum(case when totsanclimit between 1000001 and 5000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-3",
    SUM(
    CASE WHEN TOTSANCLIMIT between 1000001 and 5000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_3",
    sum(case when totsanclimit between 5000001 and 10000000  then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-4",
    SUM(
    CASE WHEN TOTSANCLIMIT between 5000001 and 10000000
    then
          (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_4",
    sum(case when totsanclimit BETWEEN  10000001 AND 200000000  then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-5",
    SUM(
    CASE WHEN TOTSANCLIMIT  BETWEEN  10000001 AND  200000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_5",
    sum(case when totsanclimit > 200000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-6",
    SUM(
    CASE WHEN TOTSANCLIMIT  >  200000000
    then
    (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_6",
    --total
    sum(
         (Case when  hrk in (13,14) THEN
                     (CASE WHEN bal4 !=0 THEN  1 else 0 END )
                  ELSE
                     (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
           end)
    )as "TotCount-7",
    SUM((Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ) AS"Total"
    from
    select
    q1.lbrcode,q1.prdacctid,q1.totsanclimit,q2.balance1,balance3,balance4,balance5,balance6,balance7,q3.hrk
    FROM
    SELECT LBRCODE,PRDACCTID,SANCDATE,TOTSANCLIMIT,RNK FROM
               SELECT
               LBRCODE,
               PRDACCTID,
               EFFFROMDATE,
               CURCD,
               PLRLINKYN,
               SANCAUTHORITY,
               SANCDATE,
               TOTSANCLIMIT,
               RANK() OVER (PARTITION BY LBRCODE,PRDACCTID ORDER BY EFFFROMDATE DESC) AS RNK
               FROM LIMIT_MAST
               WHERE LBRCODE IN (3)
    --    AND PRDACCTID LIKE 'PLLN %'
    WHERE RNK=1
    )Q1,
    (SELECT LBRCODE,PRDACCTID,CBLDATE,BALANCE1,BALANCE2,BALANCE3,BALANCE4,BALANCE5,BALANCE6,BALANCE7 FROM
    ( SELECT TRN_MAST.*,
      RANK() OVER(PARTITION BY LBRCODE,PRDACCTID ORDER BY CBLDATE DESC) AS HRK
      FROM TRN_MAST
      WHERE CBLDATE <= TO_DATE('31-MAR-2008','DD-MON-RR')
      AND (LBRCODE,TRIM(SUBSTR(PRDACCTID,1,8))) IN (SELECT LBRCODE,TRIM(PRDCD) FROM PRD_MAST
            WHERE MODULETYPE IN (13,14,30))
    )WHERE HRK=1
    )Q2,
    ( SELECT LBRCODE,TRIM(PRDCD) prd,MODULETYPE hrk FROM PRD_MAST
    WHERE (LBRCODE,TRIM(PRDCD)) IN
    (SELECT LBRCODE,TRIM(SUBSTR(PRDACCTID,1,8)) FROM LIMIT_MAST)
    )q3
    WHERE Q1.LBRCODE=Q2.LBRCODE
    AND Q1.PRDACCTID=Q2.PRDACCTID
    AND TRIM(SUBSTR(Q2.PRDACCTID,1,8))=q3.PRD
    AND Q1.LBRCODE=q3.LBRCODE
    group by lbrcode,trim(substr(prdacctid,1,8))
    order by lbrcode
    /

    Like this?
    SQL> select 123456 my_num from dual;
        MY_NUM
        123456
    SQL>
    SQL> column my_num format 999999.99
    SQL>
    SQL> select 123456 my_num from dual;
        MY_NUM
    123456.00
    SQL>Asif Momen
    http://momendba.blogspot.com

  • TOTAL IN QUERY

    Hi,
    I want to display total in query for each row like unit price + landed cost.Here unit price is always there but landed cost is applicable some times .So in some records it is blank.so in those case the total also appears as blank.
    Pls let me know how to handle this.
    Rgds,
    Rajeev

    Hi Rajeev,
    When you try to add a NULL value to another number the result is NULL, thus you should substitute NULL with 0 for e.g. ISNULL(Table.Field, 0) and then add this to the item cost, now you should get a valid value always.
    Hope this helps,
    Regards,
    Murtaza

  • Needed a running total in query

    Dear Gurus...Can I've a running total in query like this:
    Item_ Open_Qty_ Rec_Qty_ Iss_Qty_ Bal_
    A 10 5 2 13
    A 0 4 5 12
    A 0 0 6 6
    In this query column Bal is required whose value should be calculated as:
    Bal = ((Open_Qty + Rec_Qty) - Iss_Qty)
    Thanx in advance.

    389 posts and still you seem unaware of:
    - how important it is to mention your database version.
    - the tag, which implicates that you haven't read the FAQ for a while.
    - the 'search' option you have on the right side of the screen.
    You can query running totals easily by using analytic function SUM.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • SQL Help adding totals to cols..

    Hi All,
    We have a sql report that we need some help finishing please.
    The report display col data as rows and we need to total up the values at the end of the report.
    The table is as follows:
    desc all_positions
    Name                                                                     Null?    Type
    OFFICE_TYPE_DESCRIPTION                                                           VARCHAR2(60)
    POSITION_ABBREVIATION                                                             VARCHAR2(10)
    POSITION                                                                          VARCHAR2(60)
    SD                                                                                VARCHAR2(43)
    HIRED                                                                             NUMBER
    OPEN                                                                              NUMBERThe SQL select is:
    SELECT  SD
              ,SUM(open) total_open
              ,SUM(hired) total_hired
              ,COUNT(decode(a.position_abbreviation, 'POS-1', 1, NULL))   "Position 1 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-2', 1, NULL))      "Position 2 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-3', 1, NULL))   "Position 3 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-4', 1, NULL))   "Position 4 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-5', 1, NULL))   "Position 5 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-6', 1, NULL))   "Position 6 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-7', 1, NULL))   "Position 7 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-8', 1, NULL))   "Position 8 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-9', 1, NULL))   "Position 9 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-10', 1, NULL))  "Position 10 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-11', 1, NULL))  "Position 11 Header/Description"     
              ,COUNT(decode(a.position_abbreviation, 'POS-12', 1, NULL))  "Position 12 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-13', 1, NULL))  "Position 13 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-14', 1, NULL))  "Position 14 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-15', 1, NULL))  "Position 15 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-16', 1, NULL))  "Position 16 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-17', 1, NULL))  "Position 17 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-18', 1, NULL))  "Position 18 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-19', 1, NULL))  "Position 19 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-20', 1, NULL))  "Position 20 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-21', 1, NULL))  "Position 21 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-22', 1, NULL))  "Position 22 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-23', 1, NULL))  "Position 23 Header/Description"
    FROM ALL_POSITIONS a
    GROUP BY SD
    order by SD;There are 23 distinct values for "position_abbreviation" and we go through them individually working out the counts.. The report displays as follows:
    SD         TOTAL_OPEN TOTAL_HIRED Position 1 Header/Descript Position 2 H Position 3 Header         Position 4 Header   Position 5 Header/Description  ...etc all the way to the last position
    SD-10               6         816                          1            1                         1                  1                              1 
    SD-11              14         777                          0            1                         1                  1                              0 
    SD-12              59         770                          0            1                         1                  1                              0
    SD-13               2         975                          0            1                         0                  1                              0
    SD-14              78         726                          1            1                         0                  1                              0 
    SD-15              14         604                          1            1                         1                  1                              0
    SD-16             113         651                          0            1                         1                  1                              1  How can we total up cols at the end of the report? For example the report will display like the following:
    SD         TOTAL_OPEN TOTAL_HIRED     Position 1 Header/Desc Position 2      Position 3 Header/desc  Position 4 Header         Position 5 Header/Desc   ...etc all the way to the last position
    SD-10               6         816                          1            1                         1                  1                              1 
    SD-11              14         777                          0            1                         1                  1                              0 
    SD-12              59         770                          0            1                         1                  1                              0
    SD-13               2         975                          0            1                         0                  1                              0
    SD-14              78         726                          1            1                         0                  1                              0 
    SD-15              14         604                          1            1                         1                  1                              0
    SD-16             113         651                          0            1                         1                  1                              1 
    Total             286        5319                          3            7                         5                  7                              2Thanks in advance for your help.
    Regards
    Edited by: rsar001 on Nov 29, 2011 6:08 AM

    As Frank said....use rollup
    check below
    SELECT  nvl(SD,'Total')
              ,SUM(open) total_open
              ,SUM(hired) total_hired
              ,COUNT(decode(a.position_abbreviation, 'POS-1', 1, NULL))   "Position 1 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-2', 1, NULL))      "Position 2 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-3', 1, NULL))   "Position 3 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-4', 1, NULL))   "Position 4 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-5', 1, NULL))   "Position 5 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-6', 1, NULL))   "Position 6 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-7', 1, NULL))   "Position 7 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-8', 1, NULL))   "Position 8 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-9', 1, NULL))   "Position 9 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-10', 1, NULL))  "Position 10 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-11', 1, NULL))  "Position 11 Header/Description"     
              ,COUNT(decode(a.position_abbreviation, 'POS-12', 1, NULL))  "Position 12 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-13', 1, NULL))  "Position 13 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-14', 1, NULL))  "Position 14 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-15', 1, NULL))  "Position 15 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-16', 1, NULL))  "Position 16 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-17', 1, NULL))  "Position 17 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-18', 1, NULL))  "Position 18 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-19', 1, NULL))  "Position 19 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-20', 1, NULL))  "Position 20 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-21', 1, NULL))  "Position 21 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-22', 1, NULL))  "Position 22 Header/Description"
              ,COUNT(decode(a.position_abbreviation, 'POS-23', 1, NULL))  "Position 23 Header/Description"
    FROM ALL_POSITIONS a
    GROUP BY rollup(SD)
    order by SD;Edited by: newbie on Nov 29, 2011 6:20 AM

  • How to get total sum of big filtered table?

    Hello
    I'm using JDeveloper 11.1.1.3.0
    I have an af:table with big data source (100 000 rows). The table have filters.
    I want to display total count of the filtered rows and total sum by the one of column of the filtered rows in the footer of the table.
    In my backing bean I can get a Map with all filter values:
    Map<String, Object> filters = ((FilterableQueryDescriptor)table.getFilterModel()).getFilterCriteria();And, in this case, I may create the method for getting sum I need on my own.
    In this method I may create SQL Query dynamically, because I have to process all filter values with different types
    It is possible, but, maybe, there is a more easy way to do it?
    Anatolii

    Hi, sanchezis
    Code example.
    In the jsp:
                    <af:column sortProperty="Sumv" sortable="true" filterable="false" align="end" width="125px"
                               headerText="#{bindings.TransactionView1.hints.Sumv.label}" id="c16">
                      <af:outputText value="#{row.Sumv}" id="qt4">
                        <af:convertNumber maxFractionDigits="2" minFractionDigits="2"/>
                      </af:outputText>
                      <f:facet name="footer">
                          <af:panelGroupLayout id="pg41" halign="right"
                                               layout="vertical">             
                        <af:outputText value="#{backing_reptransactions.tableTransactionTotalSumV}" id="ot44">
                          <af:convertNumber maxFractionDigits="2" minFractionDigits="2"/>
                        </af:outputText>
                        </af:panelGroupLayout>
                      </f:facet>
                    </af:column>In the backing bean:
        public double getTableTransactionTotalSumV() {
            DCIteratorBinding iter =
                binding.findIteratorBinding("TransactionView1Iterator");
            TransactionViewImpl vo = (TransactionViewImpl)iter.getViewObject();
            return vo.getFilteredTotalSumV();
        }In the ViewImpl (TransactionViewImpl) class.
        public double getFilteredTotalSumV() {
            double sumV = 0d;
            DBTransaction dbTransaction = getDBTransaction();
            ResultSet rs = null;
            String query = "SELECT SUM(SumV) sumvtotal FROM (" + getQuery() + ")";
            String str1 = "WHERE ROWNUM < :Bind_RangePage_High";
            String str2 = "WHERE Z_R_N > :Bind_RangePage_Low";
            int i = query.indexOf(str1);
            if (i > 0) {
                query = query.substring(0, i) + " " + query.substring(i + str1.length());
            i = query.indexOf(str2);
            if (i > 0) {
                query = query.substring(0, i) + " " + query.substring(i + str2.length());
            PreparedStatement st = dbTransaction.createPreparedStatement(query, 0);
            try {
                Object[] params = this.getWhereClauseParams();
                int index = 0;
                for (Object avalue : params) {
                    String key = (String)((Object[])avalue)[0];
                    if ((!key.equals("Bind_RangePage_High")) &&
                        (!key.equals("Bind_RangePage_Low"))) {
                        Object value = ((Object[])avalue)[1];
                        index++;
                        if (value instanceof Integer) {
                            st.setInt(index, (Integer)value);
                        } else if (value instanceof oracle.jbo.domain.Date) {
                            st.setDate(index,
                                       ((oracle.jbo.domain.Date)value).dateValue());
                        } else if (value instanceof java.sql.Date) {
                            st.setDate(index, (Date)value);
                        } else {
                            st.setString(index, (String)value);
                rs = st.executeQuery();
                if (rs.next()) {
                    sumV = rs.getDouble("sumvtotal");
            } catch (SQLException e) {
                throw new JboException(e);
            } finally {
                if (st != null) {
                    try {
                        st.close();
                    } catch (SQLException e) {
            return sumV;
        public long getFilteredTotalCount() {
            return this.getEstimatedRowCount();
        }But, you need to know that in the TransactionView in the "General" - "Tuning" I set up next values:
    "All rows",
    "As needed",
    "Fill Last Page of Rows when Paging through Rowset",
    "Passivate State(..."
    Access Mode - "Range Paging Incremental"
    Range Size - 160
    Range Paging Cache Factor - 3
    If you have other values, then your SQL request may be different, so, you will have to rewrite it.
    I talk about
    "WHERE ROWNUM < :Bind_RangePage_High",
    "WHERE Z_R_N > :Bind_RangePage_Low",
                    if ((!key.equals("Bind_RangePage_High")) &&
                        (!key.equals("Bind_RangePage_Low")))If you have other solution, please, tell me.
    Anatolii

  • Tweaking a SUM query

    Hello experts,
    I'm working on Oracle 10g. My query needs to sample out accounts for whom, payment has been processed ( using "tracking_id" ).
    Current Table structure with sample data:
    Table BM -- around 7 million records
    account_no | balance_due
    12345 | 200
    12345 | 100
    12346 | 0
    12346 | 99.0
    Table BALANCE - 6.75 million records
    account_no | tracking_id
    12345 | 72422000
    12345 | 72422010
    12346 | 72422009
    12346 | 72422020
    I use the following Query to sample out the accounts for which payment has been processed along with their balances. The data is structured, such that, at any given time, the actual balance of the customer is the sum of all values in the " balance_due " field
    create table paid29 as
    select a1.account_no, sum(a2.balance_due) postpaid_balance
    from BM a1, BALANCE a2
    where a1.tracking_id between 72421000 and 72422050 and
    a1.account_no = a2.account_no
    group by a1.account_no; My query seems to work perfectly when the account_no's are distinct for a given payment cycle. However when there is more than one payment for a particular account ( there will be 2 tracking_id in this case for the same account) , my query seem's to be summing up the "balance_due" twice, instead of just summing up once before performing an insert. resulting in mis-match during reconciliation.
    Any help to get around this problem will be very helpful. I've tried my best to be clear with my requirements. Please let me know if anymore info is required to help me fix the query.
    Current Result:
    Table paid29
    account_no | balance_due
    12345 | 600.0
    12346 | 198.0
    Expected Result:
    Table paid29
    account_no | balance_due
    12345 | 300.0
    12346 | 99.0
    Regards,
    novice.

    You are running into Cartesian product.
    Try something like:
    SQL> With BALANCE as
      2  (
      3  SELECT 12345 account_no , 200 balance_due FROM Dual
      4  UNION ALL
      5  SELECT 12345 , 100 FROM Dual
      6  UNION ALL
      7  SELECT 12346 , 0 FROM Dual
      8  UNION ALL
      9  SELECT 12346 , 99.0 FROM Dual
    10  ),
    11  BM as
    12  (
    13  SELECT 12345 account_no, 72422000 tracking_id FROM Dual
    14  UNION ALL
    15  SELECT 12345 , 72422010 FROM Dual
    16  UNION ALL
    17  SELECT 12346 , 72422009 FROM Dual
    18  UNION ALL
    19  SELECT 12346 , 72422020 FROM Dual
    20  )
    21  -- end of test data
    22  SELECT   a1.account_no, SUM (a2.balance_due) postpaid_balance
    23      FROM (SELECT DISTINCT account_no
    24                       FROM bm
    25                      WHERE tracking_id BETWEEN 72421000 AND 72422050) a1,
    26           balance a2
    27     WHERE a1.account_no = a2.account_no
    28  GROUP BY a1.account_no;
    ACCOUNT_NO POSTPAID_BALANCE
         12346               99
         12345              300
    2 rows selected.
    SQL> Hope this helps.
    Regards,
    Jo

  • Smartform total sum

    Hi All,
    I am a newer of smartform. Now I face a problem, I want to do total sum at the bottom of main table without showed at each page. But I tried many method and it is not ok.
    Plz help me.

    Hi,
    In the node where u r printing the value , u will be printing each value in the textelement.  so Before that text elelment u create a program line.
    u take a variable and assign the variable as zero .
    in the program lines u put the code as
    variable = variable + (text-value).
    ex:-itab-menge.( uwant to make sum of menge).
    var type menge.  = 0.(This u do in global def.).
    in the program lines.
    var = var + itab-menge.
    after the loop.
    var will be sum of the all .
    Assign points if useful.

Maybe you are looking for

  • Keep getting corrupted temp save file when I save and close.

    When I save and close a numbers spreadsheet, about 20% of the time I will be left with the normal file and a weird temporary file with a "~" on the end of the file name.  I can't delete the file or do anything with it.  It will let me open it, but ev

  • How can I copy a picture from a PDF file?

    I am looking for a app that can copy a picture on a PDF to keynote or pages. I have tried iannotate and adobe reader but failed. I read the introductions of a lot of other PDF apps, such as goodreader and PDF expert, but I don't think they are equipp

  • Modbus tcp on c-rio

    Hello everyone. I already wrote an application to control via modbus tcp the plc of my brushless motor. It works fine.  Now i'd like to do the same thing using 2nd ethernet port of c-rio (just set like ni guide). It's possible this application? thank

  • Setting not using battery

    Can I chose to use only my adapter as an electric source for my mac, instead of having to use up my battery to the end? So is there a setting where you can chose to not use the battery when the adapter is plugged in? Would be nice to be able to save

  • HDV 720p60

    I have been asked to edit using the sequence HDV 720p60, but that sequence setting is not available in FCP. (I'm working in Studio2 by the way.) Is there another sequence setting they're really referring to?