Issues using SUM Function in query

I have pasted two queries Query1 (calculating counts for total_ships and ships_released) and Query2 (calculating the two same counts and then calculating SUM for total_shipments and I am having problem in this)
Query 1:
select  b.loc , b.week, b.vvalue2, b.Total_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
from (
      SELECT l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date ,  count(distinct s.ship_id ) as ships_rel_total
      FROM ship s, loct l,
         ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
      WHERE ......
      Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
      ) A,
( SELECT distinct l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
      FROM ship s, loct l,
          ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
      WHERE ......
      Group by c.loc , c.week , c.vvalue2  ) B
where a.loc (+) = b.loc
and a.vvalue2  (+) = b.vvalue2
order by b.loc, b.week , b.vvalue2,a.up_date; Query 1 Output:
*OUTPUT*
LOC         WEEK          VALUE2        TOTAL_SHIPS       DATEE         TOtAL_SHIPS_RELEASED
AA          111              BB              12                  10-05-12            2
AA          111              BB              12                  11-05-12            4
AA          111              CC              2                    14-05-12            1Then I added sum function for total_ships and its not giving me result what I need :(
Query 2:
select  b.loc , b.week, b.vvalue2, b.sum_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
from (
      SELECT l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date ,  count(distinct s.ship_id ) as ships_rel_total
      FROM ship s, loct l,
         ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
      WHERE ......
      Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
) A,
( Select  c.loc, c.week , c.vvalue2 ,  sum(c.total_ships) sum_ships 
from
    ( SELECT distinct l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
      FROM ship s, loct l,
          ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
      WHERE ......
      Group by l.loc , sr1.vvalue1 , sr.vvalue2  ) C
Group by c.loc , c.week , c.vvalue2  ) B
where a.loc (+) = b.loc
and a.vvalue2  (+) = b.vvalue2
order by b.loc, b.week , b.vvalue2,a.up_date;  my query is giving me this :(
Query 2 Output:
LOC         WEEK          VALUE2        *SUM_SHIPS*       DATEE         TOtAL_SHIPS_RELEASED
AA          111                BB              26                 10-05-12            2
AA          111                BB              26                 11-05-12            4
AA          111                CC              26                 14-05-12            1
But I need a result like this:
LOC         WEEK          VALUE2        SUM_SHIPS       DATEE         TOtAL_SHIPS_RELEASED
AA          111                BB              14              10-05-12            2
AA          111                BB              14              11-05-12            4
AA          111                CC              14              14-05-12            1

Hi,
It sounds like you have a Fan Trap , where a one-to-many relationship is causing some items to be counted many times.
The usual solution is to compute the aggregates before doing the one-to-many join. Analytic functions may make this simpler.
Sorry, I can't show you exactly how to do it without the exact data.
Post CREATE TABLE and INSERT statements for all tables involved, and also post the results you want from that data (if different from what you've already posted).
Explain, using specific examples, how you get those results from that data.
Simplify the problem as much as possible. If the problem only concerns the total_ships column, then only post the data needed to compute total_ships. This includes all the columns involved in the joins and GROUP BY clauses.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002}

Similar Messages

  • When using TODATE function MDX query is not correctly generated

    Essbase 9.3.1.2 and OBIEE 10.1.3.4.1.
    When using TODATE function MDX query is not correctly generated.
    This leads to unexpected values not only on cumulative columns in report (generated with TODATE), but also other columns (calculated with AGO function or directly read from cube) have incorrect values.
    The problem occurs when you filter on a column that is not in the select list. If you filter on just one level of dimension, results are fine. You can filter on multiple dimensions as long as you filter on just one level of each dimension.
    If you filter on two or more levels of one dimension, than results are not correct. In some cases results for TODATE column are all zeros, in some cases it is a random value returned by Essbase (same random value for all rows of that column), and in some cases BI Server returns an error:
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. Essbase Error: Network error [10054]: Cannot Send Data (HY000).
    Here is generated MDX code:
    With
    set [Grupe proizvoda2] as '{[Grupe proizvoda].[N4]}'
    set [Grupe proizvoda4] as 'Generate([Grupe proizvoda2], Descendants([Grupe proizvoda].currentmember, [Grupe proizvoda].Generations(4), leaves))'
    set [Segmentacija2] as '{[Segmentacija].[RETAIL]}'
    set [Segmentacija4] as 'Filter(Generate({[Segmentacija2]}, Descendants([Segmentacija].currentmember, [Segmentacija].Generations(4),SELF), ALL), ([Segmentacija].CurrentMember IS [Segmentacija].[AFFLUENT]))'
    set [Vrijeme3] as '{[Vrijeme].[MJESEC_4_2009]}'
    member [Segmentacija].[SegmentacijaCustomGroup]as 'Sum([Segmentacija4])', SOLVE_ORDER = AGGREGATION_SOLVEORDER
    member [Accounts].[MS1] as '(ParallelPeriod([Vrijeme].[Gen3,Vrijeme],2,[Vrijeme].currentmember), [Accounts].[Trosak kapitala])'
    member [Accounts].[MS2] as '(ParallelPeriod([Vrijeme].[Gen3,Vrijeme],1,[Vrijeme].currentmember), [Accounts].[Trosak kapitala])'
    member [Accounts].[MS3] as 'AGGREGATE({PeriodsToDate([Vrijeme].[Gen2,Vrijeme],[Vrijeme].currentmember)}, [Accounts].[Trosak kapitala])'
    select
    { [Accounts].[Trosak kapitala],
    [Accounts].[MS1],
    [Accounts].[MS2],
    [Accounts].[MS3]
    } on columns,
    NON EMPTY {crossjoin ({[Grupe proizvoda4]},{[Vrijeme3]})} properties ANCESTOR_NAMES, GEN_NUMBER on rows
    from [NISE.NISE]
    where ([Segmentacija].[SegmentacijaCustomGroup])
    If you remove part with TODATE function, the results are fine. If you leave TODATE function, OBIEE returns an error mentioned above. If you manually modify variable SOLVE_ORDER and set value to, for example, 100 instead of AGGREGATION_SOLVEORDER, results are OK.
    In all cases when this variable was modified in generated MDX, and query manually executed on Essabse, results were OK. This variable seems to be the possible problem.

    Hi,
    Version is
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    PL/SQL Release 10.2.0.5.0 - Production
    CORE    10.2.0.5.0      Production
    TNS for 64-bit Windows: Version 10.2.0.5.0 - Production
    NLSRTL Version 10.2.0.5.0 - Production
    Sorry, in my last post i forgot to mention that i already created a function based index but still it is not using because, there is a UNIQUE constraint on that column.
    Thanks

  • How can I use SUM function to calculate # of employees in the comp.&deptnt?

    I've got two tables: employee & department. I am trying to calculate total employees by department and total employees by the entire company. I know I need to use SUM function, but I only can calculate total employees by department & by company separately. I need to get this output:
    DEPT_NAME     DEPT_TOTAL_SALARY         COMPANY_TOTAL_SALARY
    RESEARCH                  10875                        29025
    SALES                      9400                        29025   
    ACCOUNTING                 8750                        29025     
    This is my code:
    SELECT department_name, SUM(salary) as total_salary
    FROM employee, department
    WHERE employee.department_id = department.department_id
    GROUP BY department_name;
    SELECT SUM(salary)
    FROM employee;
    Can somebody help please?
    Thank you in advance.Edited by: user13675672 on Jan 30, 2011 2:29 PM
    Edited by: user13675672 on Jan 30, 2011 2:31 PM

    Hi, Peter
    Peter Gjelstrup wrote:
    ... There might be a smarter way, with no re-select.You're right, as usual.
    SELECT       d.dname
    ,       SUM (e.sal)               AS dept_tot_sal
    ,       SUM (SUM (e.sal)) OVER ()     AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    GROUP BY  d.dname
    ;Analytic functions are computed after aggregate functions, so an aggregate function can be nested inside an analytic function.
    Another way (without a sub-query, at least) would be SELECT DISTINCT, with only analytic functions.
    SELECT DISTINCT
           d.dname
    ,       SUM (e.sal) OVER (PARTITION BY  d.dname)     AS dept_tot_sal
    ,       SUM (e.sal) OVER ()                    AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    ;

  • Error when using SUM function in Excel template

    I am trying to use the XDO_METADATA to create a sum of a column from my XML data and I am getting the following error in the Template Viewer:
    [111412_104246459][][PROCEDURE] Log Level is changed to PROCEDURE
    [111412_104246553][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
    Time: 0.125 sec.
    FO Formatting failed.
    <Line 317, Column 116>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
    @Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//G_CR_MST_D/V_CR_MO_IDD)"/>
    when I use:
    XDO_?SUM_V_CR_MO_IDD1?     <?sum(.//G_CR_MST_D/V_CR_MO_IDD)?>
    or
    [111412_104048508][][PROCEDURE] Log Level is changed to PROCEDURE
    [111412_104048554][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
    Time: 0.078 sec.
    FO Formatting failed.
    <Line 317, Column 105>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
    @Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//V_CR_MO_IDD)"/>
    when I use:
    XDO_?SUM_V_CR_MO_IDD1?     <?sum(.//V_CR_MO_IDD)?>
    I believe the XSL to be correct because when I change it to a count it works and when I go into BI Publisher 11g and create the query in the data model and then create a summary from it, the summary is created.
    Can anyone help?

    I went back to basics and created reports (via EXCEL templates) like I was asking based on good old EMP and DEPT and I found exactly the same problems I was mentioning. I looked at the templates provided but they were not calculating totals, like me they were selecting them and then just displaying them on the page.
    Anyway, I have narrowed it down to the fact that when you do aggregates like sum(.//SAL) this works if you have a salary for every value. I did an outer join with DEPT so I did have empty rows and why I still experienced the problems.
    Basically XSL does not like adding (including using the sum function) values that effectively have nulls in them which is why I get the cast/constructor errors because it is trying to turn a NaN value to a number and does not (or cannot) do it.
    You need to either have a value in every row of your column (maybe possible by selecting nvl in your query) and make sure that you check the "create empty nodes" checkbox in the data model of BI Publisher.,
    the other solution is an xsl solution where you would have to make sure that you only added non null values and for that you would have to investigate xsl blogs.
    It is, by the way, why my count worked because it is just counting that the record exists it does not care what the element content is or isn't.
    Closing thread.

  • Using Sum Function in Oracle(on 24 th)

    Hi all i wrote the following query.
    SELECT RESPONSER_ID,SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,COUNT(DISTINCT QUESTION_ID) AS QCOUNT FROM TQDB_LEARNER_RESPONSE WHERE RESPONSER_ID=328
    GROUP BY RESPONSER_ID
    I am getting the following error.
    ORA-00937: not a single-group group function
    Any body Pls help me.

    why use sum(sum()
    SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,
    SELECT
         RESPONSER_ID,
         SUM(DISTINCT WORK_SPACE) AS SCORE,
         COUNT(DISTINCT QUESTION_ID) AS QCOUNT
    FROM
         TQDB_LEARNER_RESPONSE
    WHERE
         RESPONSER_ID=328
    GROUP BY
         RESPONSER_ID Regards
    Singh

  • Using sum function and round function in single text form field

    Hi all,
    I have a column Name - A . In the rtf template i have summed up the column A and showing it. But the output is coming as 99.9999997. I want to round it to 100.
    I tried using <?round(sum(A),2)?> but dint workout.
    I also tried using variables. It is also not working.. I used <?xdoxslt:set_variable($_XDOCTX,’ABS',sum(A)?> and then i used get variable to get it.... But it throwing error while using sum in the set variable step.
    Can anyone please help me..
    Thanks
    Sunil

    Hi Sunil,
    Calculate the sum into a Variable. and apply round function on the variable to get the desired value.
    Calculating sum:
    <?xdoxslt:set_variable($_XDOCTX,'v',xdoxslt:get_variable($_XDOCTX,'v')+DOLLARS)?> (its running sum formula,should be placed inside the table to get sum of all rows of particular column)
    here Variable 'v' holds the sum value
    apply round function:
    <?round(xdoxslt:get_variable($_XDOCTX,'v'))?>
    Thanks and Regards,
    Aravind

  • How can i use SUM aggregate in select query?

    HI,
    GURUS,
    How can i use SUM function in Select Query and i want to store that value into itab.
    for ex:
    TABLES: vbap.
    types: begin of ty_vbap,
           incluse type vbap,
           sum type string,
          end of ty_vbap.
    data: i_vbap type TABLE OF ty_vbap,
          w_vbap type ty_vbap.
    SELECT sum(posnr) FROM vbap into table i_vbap up to 5 rows.
                            (or)
    SELECT sum(posnr) FROM vbap into table i_vbap group by vbeln.
      loop at i_vbap into w_vbap
    " which variable have to use to display summed value.
      endloop.
    if above code is not understandable pleas give ome sample code on  above query.
    Thank u,
    shabeer ahmed.

    Hi,
    Check this sample code.
    TABLES SBOOK.
    DATA:  COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
    DATA:  CONNID LIKE SBOOK-CONNID.
    SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
           INTO (CONNID, COUNT, SUM, AVG)
           FROM SBOOK
           WHERE
             CARRID   = 'LH '      AND
             FLDATE   = '19950228'
           GROUP BY CONNID.
      WRITE: / CONNID, COUNT, SUM, AVG.
    ENDSELECT.
    Regards,
    Sravanthi

  • Dont want to use group by with sum function..

    Hi all
    I am using sum function but i dont want to use group by since my query give me following output which i dont want I want.
    0------------22---------(null)     Furniture
    0-----------     3700------     (null)     अनपेड बिल्स देणे
    15800-----14202-----(null)     Petty Cash
    (null)------     (null)------ 9109     Furniture
    (null)------ (null)------ 1789     Petty Cash
    (null)-------(null)------ 0     Checking In-Transfer
    I want like
    0------------22---------9109     Furniture
    0-----------     3700------     0     अनपेड बिल्स देणे
    15800-----14202-----1789     Petty Cash
    what should be the problem how I can handle the query my query is
    select  null as totalcr, null as totaldr, (sum(acct.amtsourcecr)-sum(acct.amtsourcedr)) as opening , ev.name as accountname
    from fact_acct acct right OUTER join  c_elementvalue ev on acct.account_id= ev.c_elementvalue_id
    where acct.dateacct < '01/04/2010'
    and ev.cr_account_base=2
    group by ev.name
    UNION
    select sum(acct.amtsourcecr) as totalcr, sum(acct.amtsourcedr) as totaldr, null as opening
    *,ev.name as accountname*
    from fact_acct acct right OUTER join  c_elementvalue ev on acct.account_id= ev.c_elementvalue_id
    where  acct.datetrx BETWEEN '01/04/2010' and '01/04/2010'
    group by  ev.name
    if I remove group by it shows me error .....not a single group by function ...
    please help me out ,,,
    thanking you

    This is one way you can do it without a group by:
    SQL> with t as
      2    (
      3      select 0 amt1, 22 amt2, null amt3, 'Furniture' tag from dual union all
      4      select 15800,14202,null, 'Petty Cash' from dual union all
      5      select null, null, 9109, 'Furniture' from dual union all
      6      select null, null, 1789, 'Petty Cash' from dual
      7    )
      8  select tag, amt1, amt2, amt3
      9  from
    10  (
    11    select sum(amt1) over (partition by tag) amt1
    12          ,sum(amt2) over (partition by tag) amt2
    13          ,sum(amt3) over (partition by tag) amt3
    14          ,first_value(t.tag) over (partition by t.tag order by rownum) tag
    15          ,row_number() over (partition by t.tag order by rownum) rn
    16    from t
    17  )
    18  where rn = 1
    19  /
    TAG              AMT1       AMT2       AMT3
    Furniture           0         22       9109
    Petty Cash      15800      14202       1789

  • Please help me at this query (sum function)

    hi every one
    if I have column and the datatype is varchar2 and in this column has data like
    number,number mix varchar2,and character
    i want use sum function to summarize then number only but i want to ignore any number with char
    this example
    12
    23
    1q2
    wer
    34rt
    the result=35
    thanks in advance

    Not sure what you need here.
    However here is a sample of what's possible:
    SQL> WITH test_data AS
      2  (
      3          SELECT '12' AS DAT FROM DUAL UNION ALL
      4          SELECT '23' AS DAT FROM DUAL UNION ALL
      5          SELECT '1q2' AS DAT FROM DUAL UNION ALL
      6          SELECT '34rt' AS DAT FROM DUAL
      7  )
      8  SELECT  SUM(DAT)
      9  FROM    test_data
    10  WHERE   NOT REGEXP_LIKE(DAT,'[^[:digit:]]')
    11  /
      SUM(DAT)
            35

  • Strange error in SUM function in XI

    Hi geeks,
    We are encountering a strange issue in SUM functionality in XI.
    The Scenario is :
    We have a pipe delimited source file and INVOIC01 idoc as target.  each line in the source file will create a segment E1EDP01 in the target IDOC.
    All the values given in the file should be summed and mapped to E1EDS01 segment in the idoc.
    In one such strange case the sum of the values generated by the SUM function in XI is 2 cents lesser what we manually calculate using Calculator or Excel . There are about 100+ items in the file.  This not the case always it happens once in a while.
    Have any of you faced such strange errors. If yes please throw some light on the solution for this issue.
    Thanks,
    Noorul

    Hi folks,
    Thanks for your help. I solved this by writing my own code
    double sum = 0;
    String value;
    for (int i= 0; i< a.length; i++)
    sum = sum + Double.parseDouble(a<i>);
    value = Double.toString(sum);
    BigDecimal  bg1 = new BigDecimal(value);
    BigDecimal bg2 = bg1.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    result.addValue(bg2.toString());

  • How to use aggregate function on internal table

    hi experts,
    I am beginner in abap.I want to use sum function on internal table.
    I have structure as follow:
    types: begin of ty_ftab,
           docno TYPE bkpf-belnr,
           comcode TYPE bkpf-bukrs,
           year TYPE bkpf-gjahr,
           line_itm type bsad-buzei,
           cust type bsad-kunnr,
           amt type bsad-dmbtr,
    end of ty_ftab.
    data: it_ftab type table of ty_ftab,
               wa_ftab type ty_ftab.
    i fetched data successfully into it_ftab from bkpf and bsad table and displyed into alv.
    now i want sum of amt using group by cust and want to display like
    cust        total_amt      
    in next screen...
    displying part is not important but how can i do sum of amt according to cust value? Is there in way to query on internal table?

    Hi,
    try this code,
    data : i_sort  TYPE TABLE OF slis_sortinfo_alv
      w_sort like LINE OF i_sort.
    sort it_ftab by cust.
    w_sort-subtot = 'X'.
    w_sort-fieldname = 'AMT'.
    w_sort-tabname = 'it_ftab'.
    APPEND w_sort to i_sort.
    In fieldcatalog :
    w_fcat-fieldname = 'AMT'.
    w_fcat-tabname  = 'it_ftab'.
    w_fcat-do_sum = 'X'.
    In REUSE_ALV_GRID_DISPLAY  FUNCTION MODULE  provide the it_sort.
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
    *  EXPORTING
    *    I_INTERFACE_CHECK                = ' '
    *    I_BYPASSING_BUFFER                = ' '
    *    I_BUFFER_ACTIVE                  = ' '
    *    I_CALLBACK_PROGRAM                = ' '
    *    I_CALLBACK_PF_STATUS_SET          = ' '
    *    I_CALLBACK_USER_COMMAND          = ' '
    *    I_CALLBACK_TOP_OF_PAGE            = ' '
    *    I_CALLBACK_HTML_TOP_OF_PAGE      = ' '
    *    I_CALLBACK_HTML_END_OF_LIST      = ' '
    *    I_STRUCTURE_NAME                  =
    *    I_BACKGROUND_ID                  = ' '
    *    I_GRID_TITLE                      =
    *    I_GRID_SETTINGS                  =
    *    IS_LAYOUT                        =
    *    IT_FIELDCAT                      =
    *    IT_EXCLUDING                      =
    *    IT_SPECIAL_GROUPS                =
        IT_SORT                          =  i_sort
    *    IT_FILTER                        =
    *    IS_SEL_HIDE                      =
    *    I_DEFAULT                        = 'X'
    *    I_SAVE                            = ' '
    *    IS_VARIANT                        =
    *    IT_EVENTS                        =
    *    IT_EVENT_EXIT                    =
    *    IS_PRINT                          =
    *    IS_REPREP_ID                      =
    *    I_SCREEN_START_COLUMN            = 0
    *    I_SCREEN_START_LINE              = 0
    *    I_SCREEN_END_COLUMN              = 0
    *    I_SCREEN_END_LINE                = 0
    *    I_HTML_HEIGHT_TOP                = 0
    *    I_HTML_HEIGHT_END                = 0
    *    IT_ALV_GRAPHICS                  =
    *    IT_HYPERLINK                      =
    *    IT_ADD_FIELDCAT                  =
    *    IT_EXCEPT_QINFO                  =
    *    IR_SALV_FULLSCREEN_ADAPTER        =
    *  IMPORTING
    *    E_EXIT_CAUSED_BY_CALLER          =
    *    ES_EXIT_CAUSED_BY_USER            =
        TABLES
          t_outtab                          =
    *  EXCEPTIONS
    *    PROGRAM_ERROR                    = 1
    *    OTHERS                            = 2
      IF sy-subrc <> 0.
    * Implement suitable error handling here
      ENDIF.

  • Reg: sum() function in XML

    HI frs,
    while using sum function in Xml.not getting correct output.
    for ex:
    i have created report with emp table.
    load the xml into MS-Word.
    i want to sum total of salary of employees.
    i used SUM() function to calculate but in output it adds twice the first value and adds the rest
    for ex :
    these are values
    200
    300
    500
    i am gettting total like 1200 actually it should be 1000.
    it adds like 200+200+300+500
    why is it so.
    Regards
    Rajesh

    Hi,
    I have a problem with the 'l_booklist', I declare it as 'l_booklist  TYPE REF TO if_ixml_node' like in the interface but a shortdump comes up. must it be filled?
    greets
    Thomas

  • Sum function not showing total

    Hi,
    i have to calculate sum under the report. when i use sum function it is not displaying adding total. Please let me know. How to calcuate sum?
    Thanks,
    lax

    The sum function will work as long as you follow the rules in XPATH (check this out: http://www.w3schools.com/xpath/xpath_examples.asp)
    So, basically it depends on 1) you XML data 2) conditions for the sum.
    Assuming there are no conditions and that your xml data is flat then an example would be:
    <?sum(//MYVALUE)?>
    This will sum all elements MYVALUE in the XML data regardless of its position in the tree.
    regards
    Jorge

  • SQL Performance issue: Using user defined function with group by

    Hi Everyone,
    im new here and I really could need some help on a weird performance issue. I hope this is the right topic for SQL performance issues.
    Well ok, i create a function for converting a date from timezone GMT to a specified timzeone.
    CREATE OR REPLACE FUNCTION I3S_REP_1.fnc_user_rep_date_to_local (date_in IN date, tz_name_in IN VARCHAR2) RETURN date
    IS
    tz_name VARCHAR2(100);
    date_out date;
    BEGIN
    SELECT
    to_date(to_char(cast(from_tz(cast( date_in AS TIMESTAMP),'GMT')AT
    TIME ZONE (tz_name_in) AS DATE),'dd-mm-yyyy hh24:mi:ss'),'dd-mm-yyyy hh24:mi:ss')
    INTO date_out
    FROM dual;
    RETURN date_out;
    END fnc_user_rep_date_to_local;The following statement is just an example, the real statement is much more complex. So I select some date values from a table and aggregate a little.
    select
    stp_end_stamp,
    count(*) noi
    from step
    where
    stp_end_stamp
    BETWEEN
    to_date('23-05-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')      
    AND
    to_date('23-07-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')
    group by
    stp_end_stampThis statement selects ~70000 rows and needs ~ 70ms
    If i use the function it selects the same number of rows ;-) and takes ~ 4 sec ...
    select
    fnc_user_rep_date_to_local(stp_end_stamp,'Europe/Berlin'),
    count(*) noi
    from step
    where
    stp_end_stamp
    BETWEEN
    to_date('23-05-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')      
    AND
    to_date('23-07-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')
    group by
    fnc_user_rep_date_to_local(stp_end_stamp,'Europe/Berlin')I understand that the DB has to execute the function for each row.
    But if I execute the following statement, it takes only ~90ms ...
    select
    fnc_user_rep_date_to_gmt(stp_end_stamp,'Europe/Berlin','ny21654'),
    noi
    from
    select
    stp_end_stamp,
    count(*) noi
    from step
    where
    stp_end_stamp
    BETWEEN
    to_date('23-05-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')      
    AND
    to_date('23-07-2009 00:00:00','dd-mm-yyyy hh24:mi:ss')
    group by
    stp_end_stamp
    )The execution plan for all three statements is EXACTLY the same!!!
    Usually i would say, that I use the third statement and the world is in order. BUT I'm working on a BI project with a tool called Business Objects and it generates SQL, so my hands are bound and I can't make this tool to generate the SQL as a subselect.
    My questions are:
    Why is the second statement sooo much slower than the third?
    and
    Howcan I force the optimizer to do whatever he is doing to make the third statement so fast?
    I would really appreciate some help on this really weird issue.
    Thanks in advance,
    Andi

    Hi,
    The execution plan for all three statements is EXACTLY the same!!!Not exactly. Plans are the same - true. They uses slightly different approach to call function. See:
    drop table t cascade constraints purge;
    create table t as select mod(rownum,10) id, cast('x' as char(500)) pad from dual connect by level <= 10000;
    exec dbms_stats.gather_table_stats(user, 't');
    create or replace function test_fnc(p_int number) return number is
    begin
        return trunc(p_int);
    end;
    explain plan for select id from t group by id;
    select * from table(dbms_xplan.display(null,null,'advanced'));
    explain plan for select test_fnc(id) from t group by test_fnc(id);
    select * from table(dbms_xplan.display(null,null,'advanced'));
    explain plan for select test_fnc(id) from (select id from t group by id);
    select * from table(dbms_xplan.display(null,null,'advanced'));Output:
    PLAN_TABLE_OUTPUT
    Plan hash value: 47235625
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   1 |  HASH GROUP BY     |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   2 |   TABLE ACCESS FULL| T    | 10000 | 30000 |   159   (1)| 00:00:02 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$1
       2 - SEL$1 / T@SEL$1
    Outline Data
      /*+
          BEGIN_OUTLINE_DATA
          FULL(@"SEL$1" "T"@"SEL$1")
          OUTLINE_LEAF(@"SEL$1")
          ALL_ROWS
          OPTIMIZER_FEATURES_ENABLE('10.2.0.4')
          IGNORE_OPTIM_EMBEDDED_HINTS
          END_OUTLINE_DATA
    Column Projection Information (identified by operation id):
       1 - (#keys=1) "ID"[NUMBER,22]
       2 - "ID"[NUMBER,22]
    34 rows selected.
    SQL>
    Explained.
    SQL>
    PLAN_TABLE_OUTPUT
    Plan hash value: 47235625
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   1 |  HASH GROUP BY     |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   2 |   TABLE ACCESS FULL| T    | 10000 | 30000 |   159   (1)| 00:00:02 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$1
       2 - SEL$1 / T@SEL$1
    Outline Data
      /*+
          BEGIN_OUTLINE_DATA
          FULL(@"SEL$1" "T"@"SEL$1")
          OUTLINE_LEAF(@"SEL$1")
          ALL_ROWS
          OPTIMIZER_FEATURES_ENABLE('10.2.0.4')
          IGNORE_OPTIM_EMBEDDED_HINTS
          END_OUTLINE_DATA
    Column Projection Information (identified by operation id):
       1 - (#keys=1) "TEST_FNC"("ID")[22]
       2 - "ID"[NUMBER,22]
    34 rows selected.
    SQL>
    Explained.
    SQL> select * from table(dbms_xplan.display(null,null,'advanced'));
    PLAN_TABLE_OUTPUT
    Plan hash value: 47235625
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   1 |  HASH GROUP BY     |      |    10 |    30 |   162   (3)| 00:00:02 |
    |   2 |   TABLE ACCESS FULL| T    | 10000 | 30000 |   159   (1)| 00:00:02 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$F5BB74E1
       2 - SEL$F5BB74E1 / T@SEL$2
    Outline Data
      /*+
          BEGIN_OUTLINE_DATA
          FULL(@"SEL$F5BB74E1" "T"@"SEL$2")
          OUTLINE(@"SEL$2")
          OUTLINE(@"SEL$1")
          MERGE(@"SEL$2")
          OUTLINE_LEAF(@"SEL$F5BB74E1")
          ALL_ROWS
          OPTIMIZER_FEATURES_ENABLE('10.2.0.4')
          IGNORE_OPTIM_EMBEDDED_HINTS
          END_OUTLINE_DATA
    Column Projection Information (identified by operation id):
       1 - (#keys=1) "ID"[NUMBER,22]
       2 - "ID"[NUMBER,22]
    37 rows selected.

  • Using a function in a report query

    Why can't I call a function (basically a query) in a report query like I can from from SQL?
    Consider the following:
    Select MyFunctionName(arg) from dual;
    From SQL, it works great! No problem:
    In a report query, [Application/Shared Components/Report Queries] It doesn't work. I get an XML error:
    XML Parsing Error: not well formed
    <MyFunctionName('arg')>&lt;?xml version="1.0"?&gt;
    ----------------------^
    Why?
    Looks like APEX is not even executing the function...
    See I have a table with a CLOB field that contains properly formatted HTML. I cannot simply query for that content, since Oracle escapes the tags in the conversion to XML. I have to (somehow) tell Oracle to keep it's grubby mitts off my CLOB content. As far as I can tell, using DBMS_XMLGEN.setConvertSpecialChars is the only way to keep Oracle from escaping the html stored in the table--in fact, the DBMS_XMLGEN documentation states that it why this functionality exists in the first place!
    This is why I am trying to use a function. Simply queries don't work. The function I wrote works beautifully in SQL, but not in a report query...
    Edited by: Vorlon on Aug 5, 2010 1:20 PM

    Note from the first post:
    "In a report query, [Application/Shared Components/Report Queries]" Let me clarify: This report query is used in a BI Publisher report. Getting the information to the screen isn't the problem. I have that working. :-) It's just when I try to get the report to print that I see APEX has escaped the output before reaching BI Publisher--so BI Publisher is not the issue. I have a xsl template that will process the embedded HTML, but APEX is escaping my data before I can act on it. In other words:
    It seems Apex is not creating the XML properly, since it escapes everything. Even when the function passes back data correctly.
    Has anyone else seen this? Ideas for a workaround?
    Thanks!

Maybe you are looking for

  • While updating user Details I am gettingsome error

    Hi , While updating the user details from OIM server(OIM 9102 BP12) I am getting following error.Same is working properly on BP02.Can anybody help me to find out what is the root cause of this problem? - I am trying to ceare a user through PSFT test

  • Permit Group to logoff and shadow users (2012 R2)

    Hello everyone, I'm looking for a way to grant users permission to shadow und logoff RDS user sessions. To do this I first need to get the user's session host und unified session id: $Session = Get-RDUserSession -ConnectionBroker $ConnectionBroker -C

  • PURCHASED iTUNES NOT AUTHORIZED FOR DIGITAL EXPORT

    I am trying in vein to burn the songs I have bought in the iTunes store to a CD so I can play them in my car. However they come with a small padlock symbol in the top left corner. If I try to burn them onto a CD, a message comes up saying the song is

  • JMS using JNDI

    All, I have a fundamental question. Say for example I have given the JNDI binding information to a external application who will read and write from the message server. Would the application able to create the queues (new) on our message server wiht

  • V_V2 for reschedule of STO's

    Hi Friends I am unable to run the thansaction V_V2 for reschedule of stock transport orders. Need clues in this regard. warm regards sairam akundi