Cartesian product (sum function on 2 tables)

Dear all,
I have 2 tables with columns student_no (foreign key), date and amount in both tables.
now I want to select the sum of the amount for a student for specific date.
the following query is from stu_fee_payment table.
select sum(sfp.amount)
from stu_fee_payment sfp
where student_no =1
and sfp.pay_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
result: 200
the following query is from stu_fee_adjustment table.
select sum(sfa.adj_amount)
from stu_fee_adjustment sfa
where student_no =1
and sfa.adj_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
result: 400
now I have the following query
select sum(sfp.amount), sum(sfa.adj_amount)
from stu_fee_payment sfp, stu_fee_adjustment sfa
where sfp.student_no = sfa.student_no
and sfp.student_no =1
and sfp.pay_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
and sfa.adj_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
result: 400 400
its some kind of cartesian product because the two tables have no primary foreign key relationship.
how to solve the problem?
Regards:
MN
Edited by: Muhammad Nadeem on Aug 22, 2010 11:55 PM
Edited by: Muhammad Nadeem on Aug 23, 2010 12:58 AM

Hi Nadeem,
Try this one
SELECT sfp_sno,sfp_amount,sfa_amount
FROM
SELECT sfp.student_no sfp_sno, SUM(sfp.amount) sfp_amount
FROM stu_fee_payment sfp
WHERE sfp.pay_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
GROUP BY sfp.student_no
) x,
SELECT sfa.student_no sfa_sno, SUM(sfa.adj_amount) sfa_amount
FROM stu_fee_adjustment sfa
WHERE sfa.adj_date < TO_DATE('01-AUG-2010','DD-MON-YYYY')
GROUP BY sfa.student_no
)y
WHERE sfp_sno = sfp_no(+) Regards,
Sreekanth Munagala.

Similar Messages

  • Sum function for internal table column

    Dear Experts,
    how can I sum a complete internal table column.
    Regards
    ertas

    Hi,
    Use SUM in AT END of event in the loop of an internal table.
    Example
    Loop at ITAB into wa_itab.
    at end of wa_itab-field.
    sum.  " Here all numric fields will be summed and stored in that filed(wa_itab-field)
    endat.
    Endloop.
    Regards
    Krishna

  • Cartesian product of three dimensions - fact table is too big

    Hi, I need some advice with OLAP design. I have tables with orders, customers and product types. My problem is that I want to know amount of orders for every combination of customer - date since customer was created - product type. I also need to filter
    days when no order was made and the opposite (by dimension). Also customer have some interval of time when he is considered as a new customer and I need to filter this customers too (again by dimension).
    Now I have got fact table filled with every combination of customer/product type/date and the number of orders with the bit flag - was a new customer. Problem is that I have aprox 100k customers, so this table has bilions of rows. Is there any other possible
    solution? For browsing cube is used Excel where I cannot easily filter by measure/calculation.

    It seems like every customer is a new customer at some point in time. So, you should probably store first order date in the customer table. Depending on the Date (Period) selected , a customer will become new, active or inactive. Also, create measures for
    new customer sales, old customer sales. i.e. First order date + 30 days of the customer is less than last date in the period selected, it is new customer sales.  I would assume that it would be difficult to do it in cube. Did you
    try to solve the problem using SQL queries?
    Good luck. 
    Customer
    First Ord Date
    New customer till
    Cust A
    3/1/2014
    4/1/2014
    New Cust Sales
    Old Cust Sales
    Total Sales (New + old) 
    2014-01
    2014-02
    2014-03
    10
    10
    2014-04
    20
    20
    2014-05

  • 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.

  • Cartesian Product with @SumRange

    Hi,
    I'm trying to calculata a sumRange of an Account on two separate Dimension,on Planning 11.1.2.3
    @sumRange("Account"->"ToTal",@Range("Dimension1.1"->"Dimension2.3","Dimension1.3"->"Dimnension2.5"));
    the results is not what i was expecting, The target would be a Cartesian Product ( sum of the following elements) :
    Dimension1.1"->"Dimension2.3
    Dimension1.1"->"Dimension2.4
    Dimension1.1"->"Dimension2.5
    Dimension1.2"->"Dimension2.3
    Dimension1.2"->"Dimension2.4
    Dimension1.2"->"Dimension2.5
    Dimension1.3"->"Dimension2.3
    Dimension1.3"->"Dimension2.4
    Dimension1.3"->"Dimension2.5
    Is there any ways to achieve this ?
    Regards

    Hi,
    thanks for your eeply but the @Xrange will get  also elements that are not needed.
    if Dimension 1 has got 20 childrens (Dimension 1.1 ...Dimension 1.20) the calc will add all these elements :
    Dimension1.1"->"Dimension2.3
    Dimension1.2"->"Dimension2.3
    Dimension1.20"->"Dimension2.3
    Dimension2.1"->"Dimension2.4
    Dimension2.20"->"Dimension2.4
    Dimension1.3"->"Dimension2.3
    Dimension1.3"->"Dimension2.4
    Dimension1.3"->"Dimension2.5
    and that is incorrect.
    The elements that are needed are those in the first post.
    Regards

  • How to force Cartesian Product for unlineked (DBF) tables

    Hello
    We have been using CR8.5 for many years and we are just about to perform major upgrade to CR2011. I have, howverm found one strange behavior.
    Many of our reports are implemented in following way:
    MainTable.DBF (contains reported rows)
    ParamTable.DBF (contains one row with some general parameters)
    There is no data "link" between these tables but t makes sense to expect that every record from main table will see record from param table.
    in CR 8.5 Cartesian product of MainTable X ParamTable was ALWAYS available ad therefore we were able to (for example) hide the details & show only group totals, or display some header information (this can be also done by sub-report).
    in CR2011, however, this seems not to be the case anymore. Namely:
    any old report that I open in CR2011 has param line available only for the very first record and I was not able to find a way how to change it
    if I recreate the report from the scratch, sometimes Cartesian product is "provided" and sometimes not - I really do not know the reason for the decision.
    [I have one very ugly workaround: link these two tables with != (not equal operation) between two unrelated fields that can never be the same]
    Is there any "solution" to this cause as it blocks us from upgrading to the latest version?
    Kind Regards,
    Martin Fontan

    Hi Martin,
    Long story so here's the short one. As of CR 9 we completely redeveloped our database drivers and query engine. We removed all of the "hack" work arounds in our code for DB clients did not follow the rules, this forces the DB makers to fix the client engine and follow ANSII 92 standards. You also can no longer edit the SQL statement.
    We have also never supported unlinked tables, CR is a Relational database reporting tool. Us a subreport if you must use an unlinked table, or as you have discovered using a != type.
    Other work around is to use a Command, it' sin the Database wizard, write your own SQL, we simply pass it to the client. There is no option directly to set location from a Table to a SQL Command but search here, Brian Dong found a way around this limitation using a CR Wizard.
    Thanks
    Don

  • Joins between two tables generating Cartesian product

    Hi All,
        I am facing an issue in my report in which, I am getting mismatch as the two subsets which I'm joining is resulting in a cartesian product of individual subset's results. I am doing left join to join those two subsets. Please help in resolving
    this issue. 
    Thank you,
    Anu.

    Hi,
    Can you please post your script to see what is causing the cartesian product?
    This way it is difficult to help you.
    Regards,
    Reshma
    Please Vote as Helpful if an answer is helpful and/or Please mark Proposed as Answer or Mark As Answer when question is answered

  • Cartesian Product in Select

        Hi all!
    I need help.
    I have this function that launches a Select. My Oracle Grid tells me, when I tune the Select of this function, that there is a Cartesian Product. I understand what a Cartesian Product is, but I fail to find it. Can you help me by pointing out WHERE is the misteke? Thank you!!
    P.s. Oracle EE 10.2.0.4 on windows Server 2003 R2 SP2 64Bit
    [code]
    create or replace
    FUNCTION          "ANA_GETVERBALE"
      v_VerbaleId      IN NUMBER DEFAULT NULL,
      v_Sezione        IN VARCHAR2 DEFAULT NULL,
      v_NumeroVerbale  IN VARCHAR2 DEFAULT NULL,
      v_DataVerbale    IN DATE DEFAULT NULL,
      v_TargaVeicolo   IN VARCHAR2 DEFAULT NULL,
      v_Serie          IN VARCHAR2 DEFAULT NULL,
      v_LoggedUser IN VARCHAR2 DEFAULT NULL
    RETURN SYS_REFCURSOR
    AS
       cv_1 SYS_REFCURSOR;
    BEGIN
      OPEN cv_1 FOR
        SELECT
          ANA_M.VerbaleId,
          ANA_M.Sezione,
          ANA_M.NumeroVerbale,
          ANA_M.DataVerbale,
          ANA_M.TargaVeicolo,
          ANA_M.Serie,
          SCH_C.StatoCartellinoId,
          LOV_StatoCartellino.ListOfValueName StatoCartellino,
          sch_c.cartellinoid
        FROM ANA_Materia_Verbale ANA_M
        INNER JOIN SCH_Cartellini SCH_C ON SCH_C.SoggettoId=ana_m.verbaleid AND SCH_C.TipoSoggettoId = SIS_CONSTANTS_PKG.VB
        INNER JOIN SIC_PROFILO_STATO SIC_PSC ON SIC_PSC.STATOID=SCH_C.STATOCARTELLINOID
        INNER JOIN SIC_PROFILI_USERS SIC_PUC ON SIC_PUC.PROFILOID=SIC_PSC.PROFILOID AND SIC_PUC.PERSONALID=v_LoggedUser
        LEFT JOIN TYP_ListOfValues LOV_StatoCartellino  ON LOV_StatoCartellino.ListOfValueId = SCH_C.StatoCartellinoId
        WHERE ( v_VerbaleId = SIS_CONSTANTS_PKG.AnyBigint OR ANA_M.VerbaleId = v_VerbaleId )
          AND ( v_Sezione = SIS_CONSTANTS_PKG.AnyString OR REGEXP_LIKE(ANA_M.Sezione, '^' || v_Sezione || '$', 'i') )
          AND ( v_serie = SIS_CONSTANTS_PKG.AnyString OR REGEXP_LIKE(ANA_M.Serie, '^' || v_Serie || '$', 'i') )
          AND ( v_NumeroVerbale = SIS_CONSTANTS_PKG.AnyString OR ANA_M.NumeroVerbale = v_NumeroVerbale )
          AND ( v_DataVerbale = SIS_CONSTANTS_PKG.AnyDateTime OR ANA_M.DataVerbale = v_DataVerbale )
          AND ( v_TargaVeicolo = SIS_CONSTANTS_PKG.AnyString OR REGEXP_LIKE(ANA_M.TargaVeicolo,'^' || v_TargaVeicolo || '$', 'i') );
      RETURN cv_1;
    END;
    [/code]

    ....ouch... well that explains a LOT!! The real problem was the Oracle Grid SQL_TUNING that warned me that the SELECT contained a CARTESIAN PRODUCT:
    Ristruttura SQL
    An expensive cartesian product operation was found at line ID 4 of the execution plan.
    Consider removing the disconnected table or view from this statement or add a join condition which refers to it.
    A cartesian product should be avoided whenever possible because it is an expensive operation and might produce a large amount of data.
    with this EXECUTION PLAN:
    Operazione
    ID riga
    Oggetto
    Object type
    Ordine
    Righe
    Dimensione (KB)
    Costo
    Tempo (sec)
    Costo CPU
    Costo I/O
    SELECT STATEMENT
    0
    13
    1
    0,091
    460
    6
    116.852.560
    452
    NESTED LOOPS OUTER
    1
    12
    1
    0,091
    460
    6
    116.852.560
    452
    NESTED LOOPS
    2
    9
    1
    0,079
    459
    6
    116.843.328
    451
    NESTED LOOPS
    3
    7
    2
    0,141
    457
    6
    116.826.984
    449
    MERGE JOIN CARTESIAN
    4
    4
    2
    0,102
    451
    6
    116.781.136
    443
    INDEX FAST FULL SCAN
    5
    DOCARK.PK_SIC_PROFILI_USERS
    INDEX (UNIQUE)
    1
    1
    0,010
    2
    1
    81.903
    2
    BUFFER SORT
    6
    3
    2
    0,082
    449
    6
    116.699.232
    441
    TABLE ACCESS FULL
    7
    DOCARK.ANA_MATERIA_VERBALE
    TABLE
    2
    2
    0,082
    449
    6
    116.699.232
    441
    TABLE ACCESS BY INDEX ROWID
    8
    DOCARK.SCH_CARTELLINI
    TABLE
    6
    1
    0,020
    3
    1
    22.924
    3
    INDEX RANGE SCAN
    9
    DOCARK.IDX_SCH_CARTELLINI_SOG_TIPO
    INDEX
    5
    1
    2
    1
    15.493
    2
    INDEX RANGE SCAN
    10
    DOCARK.PK_SIC_PROFILO_STATO
    INDEX (UNIQUE)
    8
    1
    0,009
    1
    1
    8.171
    1
    TABLE ACCESS BY INDEX ROWID
    11
    DOCARK.TYP_LISTOFVALUES
    TABLE
    11
    1
    0,012
    1
    1
    9.231
    1
    INDEX UNIQUE SCAN
    12
    DOCARK.PK_TYP_LISTOFVALUES
    INDEX (UNIQUE)
    10
    1
    0
    1
    1.900
    0
    So I started trying to REMOVE the Cartesian Product. But first I had to find it! So apparently I shouldn't worry too much...
    The real problem is that I have to work with funtions and DBs created by others, so I am not sure what to expect from most of the Functions. Apparently this execution is correct no matter what that the Tunig Advisor says!
    Thanks!

  • Want to avoid cartesian Product but cannot avoid it some how.

    Hi,
    I am using oracle 10G .
    trying to draft a query which is resulting in absurd results.
    select i.corr_acc_no, sum(amtsign.amount_6) from item i,
    (select corr_Acc_no,flag_2,decode(fund_code,'C',amount_6,amount_6*-1) amount_6 from item
    where corr_AcC_no in (select corr_acc_no from bank where local_Acc_no in ('MBL-SEG-NZD'))and flag_2=0) AmtSign
    where i.corr_acc_no=amtsign.corr_acc_no
    and i.flag_2=0
    group by  i.corr_acc_no
    Basically the inner query, which i am using as the second table in the join, gives 13 results. I want to sum the amount_6 field in main select clause which I want to get from results of
    (select corr_Acc_no,flag_2,decode(fund_code,'C',amount_6,amount_6*-1) amount_6 from item
    where corr_AcC_no in (select corr_acc_no from bank where local_Acc_no in ('MBL-SEG-NZD'))and flag_2=0)
    The sum took too much time so i drafted simple query to check how many rows are returned by removing sum and i noticed it gives a Cartesian product with 169 rows instead of just 13. I have 2 join conditions but the value for corr_Acc_no is same for all 13 rows, i can't use amount_6 as join becuase i am changing it's sign  in the inner query. Please advise.

    Thanks to both of you. @LakmalRajapakse your answer is bang on right. I did the same way after I posted this. I realized there's no point joining item with itself when I can get it done in single query. It's just that I was having hard time with 'Case' in select to get whatever I want,so I tried this logic. But then gave a try to decode, it worked. Thanks anyways.

  • CARTESIAN PRODUCT problem

    hello,
    i m trying to find the difference for calculating the DIFFENCE IN STOCK FOR OPC,PPC,CLINKER BY USING FOLLOWING SQL-QUERY
    SELECT TO_CHAR(a.dateofmtrl,'YYYY') YEAR,
    SUM(a.rm1) - SUM(b.rm1) - SUM(c.rm1) OPC,
    SUM(a.rm2) - SUM(b.rm2) - sum(c.rm2) PPC,
    SUM(a.rm3) - SUM(b.rm3) - sum(c.rm3) CLINKER
    FROM rawmtrl_graph a
    INNER JOIN rawmtrl_graph b ON TO_CHAR(a.dateofmtrl,'YYYY') =TO_CHAR(B.dateofmtrl,'YYYY')
    INNER JOIN rawmtrl_graph c ON TO_CHAR(a.dateofmtrl,'YYYY') =TO_CHAR(C.dateofmtrl,'YYYY')
    WHERE a.mtrl_flag='P'
    AND b.mtrl_flag='D'
    AND c.mtrl_flag='CS'
    GROUP BY TO_CHAR(a.dateofmtrl,'YYYY')
    BUT IT IS GIVING CARTESIAN PRODUCT...
    HOW TO MODIFY THE QUERY FOR FINDING EXACT FIGURE??????
    THANKS IN ADVENCE FOR ANY HELP.....

    Hi,
    please always put your code between two lines starting with {noformat}{noformat}.
    Additionally when you put insert statement put them entirely and not copying from one table we don't have.
    Here the way to get the result you want:SELECT EXTRACT(YEAR FROM dateofmtrl) yr
    , SUM(CASE mtrl_flag WHEN 'P' THEN rm1 ELSE -rm1 END) AS opc
    , SUM(CASE mtrl_flag WHEN 'P' THEN rm2 ELSE -rm2 END) AS ppc
    , SUM(CASE mtrl_flag WHEN 'P' THEN rm3 ELSE -rm3 END) AS clinker
    FROM rawmtrlgraph
    GROUP BY EXTRACT(YEAR FROM dateofmtrl);
    YR OPC PPC CLINKER
    2011 50 54 55
    2012 -49 -3 -11
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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}

  • Best performance in a cartesian product

    i've got a select that needs a cartesian product.
    ex:
    SELECT NVL(a.year,cp.year) year, NVL(a.month,cp.month), NVL(a.value,0) value
    FROM
    (select year, month from year, month) cp, values a
    WHERE cp.year = a.year(+) AND cp.month = a.month(+)
    i have to show all records possible even if they don't have any values on the table.
    In the beginning with fewer values, it ran OK.... but now with a lot more it begins to take a little longer (about 10 times longer).
    What is the best way to improve this kind of selects???
    Thank you.

    Best Case :
    No one shold be in red color in analysis is the best runtime.
    All should be in Green.
    or
    OK Case :
    Database level - Red is not acceptable
    ABAP Level - Red can be accepted and can be a good runtime.
    System Level - Red is not acceptable.
    Worst Case:
    All are in Red Color

  • Require sum value of one table to be inserted into another table column

    Hi
    I have a table which contains a list of parts and their prices required for an assembly.
    I am trying to calculate the total from this part lists and put into the total price column for the assembly (another table column).
    My method was to calculate the total in a page process ( eg, once all parts in the assembly have been entered the page process calculates the total price (the sum of the part prices at that time) and puts the result (total) in the assembly total column)
    In the process I capture the total using either
    SELECT SUM(TOTAL_COST) Total INTO B from CC_REQ_BOM WHERE RID = :P5_RID;
    or
    SELECT SUM(TOTAL_COST) INTO B from CC_REQ_BOM WHERE RID = :P5_RID;
    Both the above sql statements are allowed ( one with alias and one without alais) by the page process but they dont seem to be working as no total is returned to the table when the page process is run.
    to insert the calculation(variable B) into the required table I have used
    INSERT INTO CC_REQ(TOTAL_COST)
    VALUES(B);
    I have used this method a few times with no problems for standard sql statements but this is the first time I have used it with the sum SQL function. For some reason it doesn't seem to like the SUM function even though the code below works in SQL Command window.
    SELECT SUM(TOTAL_COST) from CC_REQ_BOM WHERE RID = :P5_RID;
    Any help welcome.
    PGJ

    Hi
    In that case, I would do something like this then...
    CREATE TABLE crt_crates
    (ccr_id   INTEGER        CONSTRAINT ccr_pk PRIMARY KEY,
    ccr_name VARCHAR2(4000) CONSTRAINT ccr_nam_nn NOT NULL);
    CREATE TABLE crt_requests
    (cre_id        INTEGER        CONSTRAINT cre_pk PRIMARY KEY,
    cre_reference VARCHAR2(4000) CONSTRAINT cre_ref_nn NOT NULL,
    --I've skipped the requester as this would probably refernce a different table
    --I've skipped request details as it's not necessary for this example
    cre_ccr_id    INTEGER        CONSTRAINT cre_ccr_fk REFERENCES crt_crates);
    CREATE TABLE crt_materials
    (cma_id   INTEGER        CONSTRAINT cma_pk PRIMARY KEY,
    cma_name VARCHAR2(4000) CONSTRAINT cma_nam_nn NOT NULL,
    cma_cost NUMBER(12,2)   CONSTRAINT cma_cos_nn NOT NULL);
    CREATE TABLE crt_crate_bom
    (ccb_id       INTEGER CONSTRAINT ccb_pk PRIMARY KEY,
    ccb_ccr_id   INTEGER CONSTRAINT ccb_ccr_fk REFERENCES crt_crates,
    ccb_cma_id   INTEGER CONSTRAINT ccb_cma_fk REFERENCES crt_materials,
    ccb_quantity INTEGER DEFAULT 1 CONSTRAINT ccb_qua_nn NOT NULL);
    INSERT INTO crt_crates
    VALUES(1, 'Crate 1');
    INSERT INTO crt_requests
    VALUES(1,'Request 1',1);
    INSERT INTO crt_materials
    VALUES(1,'Material 1', 1000);
    INSERT INTO crt_materials
    VALUES(2,'Material 2', 500);
    INSERT INTO crt_crate_bom
    VALUES(1,1,1,5);
    INSERT INTO crt_crate_bom
    VALUES(2,1,2,3);
    COMMIT;
    --So crate cost totals would be...
    SELECT cre_reference              request,
           ccr_name                   crate,
           SUM(cma_cost*ccb_quantity) crate_cost
    FROM   crt_requests,
           crt_crates,
           crt_materials,
           crt_crate_bom
    WHERE  cre_ccr_id = ccr_id
    AND    ccb_ccr_id = ccr_id
    AND    ccb_cma_id = cma_id
    GROUP BY cre_reference,
             ccr_name;
    --And request cost totals would be...
    SELECT cre_reference              request,
           SUM(cma_cost*ccb_quantity) crate_cost
    FROM   crt_requests,
           crt_crates,
           crt_materials,
           crt_crate_bom
    WHERE  cre_ccr_id = ccr_id
    AND    ccb_ccr_id = ccr_id
    AND    ccb_cma_id = cma_id
    GROUP BY cre_reference; Do you see what I mean - you don't store the derived values as they could get out of sync with the component parts that make then up. You derive them from the underlying data instead.
    Hope this makes sense.
    Cheers
    Ben

  • Urgent plz help me out about cartesian product

    plz...its urgent,can anyone help in the following query where iam getting cartesian product,so how to get result without cartesian product
    this is the query
    SELECT DISTINCT MIS.segment1 "ITEM CODE",
    MIS.DESCRIPTION "DESCRIP"
    ,MIS.Primary_uom_code "UOM",
    MTL.LOT_NUMBER "LOT NUMBER"
    ,A.PARTY_NUMBER "CUSTOMER NUMBER",
    A.PARTY_NAME "CUSTOMER NAME",
    (A.ADDRESS1||A.ADDRESS2||A.ADDRESS3||A.ADDRESS4) "SHIP TO",
    B.DELIVERY_DETAIL_ID "DO NO",B.SHIPPED_QUANTITY "SHIPPED QUANTITY"
    ,C.ULTIMATE_DROPOFF_DATE "ISSUED DATE"
    ,D.ORDER_NUMBER "SALES ORDER NUMBER"
    ,E.LINE_NUMBER "SALES ORDER LINE"
    FROM MTL_SYSTEM_ITEMS MIS
    ,MTL_TRANSACTION_LOT_NUMBERS MTL
    ,HZ_PARTIES A,
    WSH_DELIVERY_DETAILS B,
    WSH_NEW_DELIVERIES C,
    OE_ORDER_HEADERS_ALL D,
    OE_ORDER_LINES_ALL E
    WHERE MIS.INVENTORY_ITEM_ID=MTL.INVENTORY_ITEM_ID
    AND B.INVENTORY_ITEM_ID=MIS.INVENTORY_ITEM_ID
    AND A.PARTY_ID=B.CUSTOMER_ID
    AND B.DELIVERY_DETAIL_ID=C.DELIVERY_ID
    AND MIS.INVENTORY_ITEM_ID=E.INVENTORY_ITEM_ID
    AND D.HEADER_ID=E.HEADER_ID

    A lot of times when I get duplicate results, I'll do a select * and see why. Often one of those tables will have a sequenced value that could repeat several times for a combination of values.
    If thats the case, you may need to add something like:
    ...and a.id = (select min(id)
                     from b
                    where a.col = b.col)

  • How can I sum up raws? the sum function seems to work for columns only and right now I have to create a separate formula for each raw

    How can I sum up raws? the Sum function seems to work only on columns. Right now I have to create a separate formula for each raw

    Hi dah,
    "Thanks, but can I do one formula for all present and future raws? as raws are being added, I have to do the sum function again and again"
    You do need a separate formula for each group of values to be summed.
    If the values are in columns, you need a copy of the formula for each column.
    If the values are in rows, you need a copy of the formula for for each row.
    If you set up your formulas as SGIII did in his example (shown below), where every non-header row has the same formula, Numbers will automtically add the formula to new rows as you add them.
    "Same formula" in this context means exactly the same as all the formulas above, with one exception: the row reference in each formula is incremented (by Numbers) to match the row containing the formula.
    Here the formula looks like this in the three rows shown.
    B2: =SUM(2)
    B3: =SUM(3)
    B4: =SUM(4)
    That pattern will continue as rows are added to the table.
    Also, because the row token (2) references all of the non-header cells in row 2, the formula will automatically include new columns as they are added to the table.
    Regards,
    Barry

Maybe you are looking for

  • TS3988 I have an iCloud account but I don't know how to get there from my iMac finder

    I have an iCloud account but I can figure out how to get to it from Finder

  • DB statistics error in batch job in BW system

    Hi, The job DB statistics run in the background every week. But now the job looks finished in SM37 but the job log shows errors. Below is the job log. 08.01.2008 01:00:07 Job started                                                                 08.

  • Maintanence plan jobs are failing

    Dear All, We are facing problems with maintenance plan jobs in SQL server 2012. All jobs are failing with Following error Executed as user: Testdbserver\SQLadmuser. Microsoft (R) SQL Server Execute Package Utility  Version 11.0.3431.0  for 64-bit  Co

  • Music Player that supports FLAC?

    Hi, Have just bought a ZTE Open with Firefox OS, and have been looking forward to it arriving. Got it yesterday and am generally very happy, BUT my entire music collection is in FLAC, and it seems that: a) the default music player doesn't support FLA

  • Unable to Open Application - Xlib: connection to "localhost:10.0" refused by ser

    Hello, I have Tarantella installed on Fedora Core 2. I am accessing the WebTop from Windows XP machine. After logging in with Administrator account when I click on kedit nothing happens so I clicked on show details and I found below log. I really don