Aggregation Function With Joining

Hi all,
I've the following SQL Query and I want to add a join with it:
SELECT Collected_Goods.ProductId, SUM(Collected_Goods.Amount)
FROM Collected_Goods
GROUP BY Collected_Goods.ProductIdand I want to replace or add (but replace is better) the Collected_Goods.ProductId with a Products.Name where the product name appears in another table called products. Also I want the aggregation function SUM to work on Collected_Goods.ProductId
The FK in Collected_Goods to Products is Collected_Goods.ProductId and Products.Id
Thanks in advance
Edited by: ZiKaS on Dec 30, 2008 2:05 AM

The output for the above one is like this
Collected_Goods.ProductId     |     SUM(Amount)
                             1           |        60     
                             2           |        32
                             .            |         .
                             .            |         .
                             .            |         .
I want it to be something link this
Products.Name                     |     SUM(Amount)
                             Milk        |        60     
                             Butter    |        32
                             .            |         .
                             .            |         .
                             .            |         .                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Create a View with Aggregation Function (COUNT)

    I've been looking up and down for a way to create a view with a few basic fields and some other fields containing aggregation function.
    For instance:
    To display a view that contain all the Contract Agreement and the corresponding count of the PO releases.
    Agreement Nbr, Total PO releases
    I need this view so that I can create a search help with this view.
    I found something about the "CREATE VIEW" statement, but I don't have any idea how to use it.
    Any helps toward this matter is very much appreciated, thanks.

    Hello Aldern
    I guess you have read about the SQL statement "CREATE VIEW". When we create a view in the dictionary this SQL statement is finally called to create the view on the DB. Thus, since we do not have any aggregation options in views you cannot achieve what you want using views.
    The solution for your problem is to create a <b>search help</b> having a <b>search help exit</b>. Within the exit you can do your aggregation functions and add these values to the displayed search help data.
    Regards
      Uwe

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • Join numeric with join numbers function

    Hi !  a small question from a guy that didnt use labview for a while !
    i need to use the join number function to join two DBL number A and B to form a new number A.B, just like the join numbers function
    in the example i would like the results after the join number function to be 1.5 
    however i understand that the function merge bytes/words together and the result is far from what i expect ....  any ways to 
    A and B are extracted from modbus READ register command and are unsigned 16 bit
    seems easy enough but i need a good refreshment on how those bits, bytes and numeric works together..   doh !
    thank for everyone involved, Kudos to all labview champions!
    Solved!
    Go to Solution.
    Attachments:
    join numbers.png ‏108 KB
    test comm.png ‏91 KB

    Hi yan,
    it seems you really need a refreshment on all those bits/bytes/numeric representations
    Typecasting floats (DBL) to U16 will probably never result in the desired value.
    Why do you convert your U16 modbus values to DBL anyway? Stick with U16 and you will have no problems using JOIN or any other bit-banging function...
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Update with join

    Hello Everybody
    I have 3 tables in a maxdb 7.6 database
    rbarbeitsplanpos key=rbarbeitsplanposid column gewichtung,...
    rbaplposausf key=rbaplposausfid columns rbarbeitsplanposid,...
    rbqspruefpos key=rbqspruefposid columns rbaplposausfid,gewichtung,...
    Now i want to update gewichtung in rbqspruefpos with the value of gewichtung in the corresponding record in rbarbeitsplanpos.
    The way to find the correct value is:
    From rbqspruefpos with rbaplposausfid into rbaplposausf  
    From rbaplposausf with rbarbeitsplanposid to rbarbeitsplanpos
    I found this hit:
    A simple example of the power of including joins in an Update Statement:
    Update Tbl1 set tbl1.field1=tbl2.field2*.10,
    from Tbl1 join tbl2 on tbl1.PKfield=tbl2.tbl1FK
    This will update all the joined rows in tbl1 to 10% of the values in tbl2.
    I code:
    update rbqspruefpos set gewichtung =  rbarbeitsplanpos.gewichtung,
    from rbqspruefpos
    join  rbaplposausf on rbqspruefpos.rbaplposausfid = rbaplposausf.rbaplposausfid
    join rbarbeitsplanpos on rbarbeitsplanpos.rbarbeitsplanposid = rbaplposausf.rbarbeitsplanposid
    General error;-5016 POS(73) Missing delimiter: =
    This one works without errors:
    update rbqspruefpos set gewichtung = (select rbarbeitsplanpos.gewichtung  from rbarbeitsplanpos
    join  rbaplposausf on rbarbeitsplanpos.rbarbeitsplanposid = rbaplposausf.rbarbeitsplanposid
    join rbqspruefpos on rbqspruefpos.rbaplposausfid = rbaplposausf.rbaplposausfid)
    but all rbqspruefpos.gewichtung are filled with the same value?
    The first value found in rbarbeitsplanpos.
    Any help welcomed
    Best regards
    Albert

    > I code:
    > update rbqspruefpos set gewichtung =  rbarbeitsplanpos.gewichtung,
    > from rbqspruefpos
    > join  rbaplposausf on rbqspruefpos.rbaplposausfid = rbaplposausf.rbaplposausfid
    > join rbarbeitsplanpos on rbarbeitsplanpos.rbarbeitsplanposid = rbaplposausf.rbarbeitsplanposid
    >
    >  General error;-5016 POS(73) Missing delimiter: =
    >
    >
    > This one works without errors:
    > update rbqspruefpos set gewichtung = (select rbarbeitsplanpos.gewichtung  from rbarbeitsplanpos
    > join  rbaplposausf on rbarbeitsplanpos.rbarbeitsplanposid = rbaplposausf.rbarbeitsplanposid
    > join rbqspruefpos on rbqspruefpos.rbaplposausfid = rbaplposausf.rbaplposausfid)
    >
    > but all rbqspruefpos.gewichtung are filled with the same value?
    > The first value found in rbarbeitsplanpos.
    Looks like you're doing it wrong.
    Subselects need to be enclosed in brackets.
    See [Subquery (subquery)|http://maxdb.sap.com/doc/7_6/60/515f3eca2a11d2a97100a0c9449261/content.htm]
    Only scalar subselects (these are the ones that by their very structure can only produce zero or one rows in the result set) can omit the brackets.
    The database cannot know that there is only one value in this column - you may try and put a aggregation function round it.
    regards,
    Lars

  • Aggregation function for field in ALV Webdynpro ABAP

    Dear all,
    Can I create aggregation function on one field of ALV WDA which that is currency type field and then display the result based on currency key field?
    i've tried using code as shown below
      lo_wd_field = lo_model->if_salv_wd_field_settings~get_field( 'TOTAL' ).
      DATA: lo_field_aggr TYPE REF TO cl_salv_wd_aggr_rule.
      lo_field_aggr = lo_wd_field->if_salv_wd_aggr~create_aggr_rule( ).
      CALL METHOD lo_field_aggr->set_aggregation_type
        EXPORTING
          value = if_salv_wd_c_aggregation=>aggrtype_total.
      lo_wd_field->set_reference_field_type( if_salv_wd_c_field_settings=>reffieldtype_curr ).
      lo_wd_field->set_reference_field( 'WAERS' ).
    and then i've tried enabled standard function as shown below
    lo_model->if_salv_wd_std_functions~set_aggregation_allowed( abap_true ).
    But Why result of aggregation is not formatted based on currency key?
    Best regards,
    Agnis Virtinova Avency

    Hi Virtonova,
    My requirement is also simillar.
    I want to aggregate total based on Currency key.
    In the total for sub groups and final total with out any text or Description getting only single or double or triple ( dots ). .
    Is it possible to populate / change with useful text or decription for those rows.
    I am not getting Currency type after the total/sub totals.
    how to fix this in ALV list after using aggregate for the ALV.
    Thanks in advance.
    Dav

  • User Defined Function VS join - Performance....

    Hi All,
    while linking the mulitple table and getting the values ....which one is the best ?
    Joining or User defined function.....
    single row function
    select a.name , get_salary(empid) from emp a;
    Note : get_salary function will return the salary from salary tables.
    Using joins
    select a.name ,b.salary from emp a, salary b
    where a.empid=b.empid;
    which is the performancewise best ?
    also if you give any related document also fine.
    Thanks in advance.
    Edited by: BASKAR NATARAJAN on Jan 6, 2011 10:09 PM

    Don't use such functions for joins. The function itself has to query the salary table. It will run the query against the salary table separately for each row that it reads from the emp table. You will end up with multiple recursive calls and possibly inconsistency in the output. (Imagine what would happen if the salary table were updated and commited while this query was running -- some rows would have been read with the pre-update values and others with the updated values).
    Specifying the join in the query ensures that a single SQL call is executed and provides read consistency across all the rows it reads. And it is much faster, being one single parse and execute.
    Hemant K Chitale
    http://hemantoracledba.blogspot.com

  • Materialized View  with Joins and Possibilities of Partitioning

    Hi,
    We have a materialized view which has a data to query around 12 gb. The query goes some thing like
    this.
      Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
      from a,b,c
      where a.c1=b.c1
      --and the where condition goes on...
      --i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
       Now i have few questions here.
    Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
    Question No 1
    Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
    Question No 2
    Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
    Question No 3
    How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
    Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
    Thanks in anticipation for a good round of discussion

    Hi,
    We have a materialized view which has a data to query around 12 gb. The query goes some thing like
    this.
      Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
      from a,b,c
      where a.c1=b.c1
      --and the where condition goes on...
      --i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
       Now i have few questions here.
    Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
    Question No 1
    Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
    Question No 2
    Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
    Question No 3
    How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
    Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
    Thanks in anticipation for a good round of discussion

  • How can I use AGO function with aggregates

    I use aggregated table and a detailed table
    I have time hierarchy whose lowest level is date. For sales I
    created year-to-year (YTD) comparision with AGO function. It
    works OK.
    BUT, I want to speed it up, so I used aggregates. I created new
    time table grouped by MONTH and corresponding agg_SALES table. I
    created connections and mapped the fields. It works OK for
    normal queries, that means my queries at month level use
    aggregates. BUT when I add YTD measures or YAGO measure in query, it goes to
    then SALES table whose grain is date.
    How can I force BI Server to use AGO function with aggregates?
    I use OBIEE 10.1.3.4
    Thank you
    Ishaq
    (Question originally taken from ITtoolbox and posted by Gorazd)
    SORRY - THE QUESTION IS IN THE WRONG FORUM
    Edited by: ishaq12 on Nov 19, 2008 12:21 PM

    Hi,
    you can not do it in Administration tool but you can set agregation for that field in Answers (fx->Agregation rule->Sum) and effect should be the same. Note that it may not work properly on Oracle 10g as generated SQL is not 100% recognized, on 11g everything is OK (at least in my case).
    Regards,
    Marko
    Edited by: user10449532 on 2008.11.19 06:29

  • Pipelined Function with execute immediate

    Hello Experts,
    I have created a Pipe lined function with execute immediate, due to below requirement;
    1) Columns in where clause is passed dynamically.
    2) I want to know the data stored into above dynamic columns.
    3) I want to use it in report, so I don't want to insert it into a table.
    I have created a TYPE, then through execute immediate i have got the query and result of that query will be stored in TYPE.
    But when calling the function i am getting
    ORA-00932: inconsistent datatypes: expected - got -
    Below is my function and type, let me know i am going wrong, and is my logic correct.
    CREATE OR REPLACE TYPE OBJ_FPD AS OBJECT
                      (LOW_PLAN_NO VARCHAR2 (40),
                       FPD VARCHAR2 (5),
                       SERIAL_NO NUMBER,
                       CEDIA_CODE VARCHAR2 (2),
                       DT DATE);
    CREATE OR REPLACE TYPE FPD_TBL_TYPE AS TABLE OF OBJ_FPD;
    CREATE OR REPLACE FUNCTION FUNC_GET_FPD_DATE (P_LOW_PLAN_NO    VARCHAR2,
                                                  P_CEDIA_CODE     VARCHAR2,
                                                  P_SERIAL_NO      NUMBER)
       RETURN FPD_TBL_TYPE
       PIPELINED
    AS
       CURSOR C1
       IS
              SELECT 'FPD' || LEVEL TBL_COL
                FROM DUAL
          CONNECT BY LEVEL <= 31;
       V_STR        VARCHAR2 (5000);
       V_TBL_TYPE   FPD_TBL_TYPE;
    BEGIN
       FOR X IN C1
       LOOP
          V_STR :=
                'SELECT A.low_PLAN_NO,
               A.FPD,
               A.SERIAL_NO,
               A.cedia_code,
               TO_DATE (
                     SUBSTR (FPD, 4, 5)
                  || ''/''
                  || TO_CHAR (C.low_PLAN_PERIOD_FROM, ''MM'')
                  || ''/''
                  || TO_CHAR (C.low_PLAN_PERIOD_FROM, ''RRRR''),
                  ''DD/MM/RRRR'')
                  DT FROM ( SELECT low_PLAN_NO, '
             || ''''
             || X.TBL_COL
             || ''''
             || ' FPD, '
             || X.TBL_COL
             || ' SPTS, SERIAL_NO, cedia_code FROM M_low_PLAN_DETAILS WHERE NVL('
             || X.TBL_COL
             || ',0) > 0 AND SERIAL_NO = '
             || P_SERIAL_NO
             || ' AND cedia_code = '
             || ''''
             || P_CEDIA_CODE
             || ''''
             || ' AND low_PLAN_NO = '
             || ''''
             || P_LOW_PLAN_NO
             || ''''
             || ') A,
               M_low_PLAN_DETAILS B,
               M_low_PLAN_MSTR C
         WHERE     A.low_PLAN_NO = B.low_PLAN_NO
               AND A.cedia_code = B.cedia_code
               AND A.SERIAL_NO = B.SERIAL_NO
               AND B.low_PLAN_NO = C.low_PLAN_NO
               AND B.CLIENT_CODE = C.CLIENT_CODE
               AND B.VARIANT_CODE = C.VARIANT_CODE
    CONNECT BY LEVEL <= SPTS';
          EXECUTE IMMEDIATE V_STR INTO V_TBL_TYPE;
          FOR I IN 1 .. V_TBL_TYPE.COUNT
          LOOP
             PIPE ROW (OBJ_FPD (V_TBL_TYPE (I).LOW_PLAN_NO,
                                V_TBL_TYPE (I).FPD,
                                V_TBL_TYPE (I).SERIAL_NO,
                                V_TBL_TYPE (I).CEDIA_CODE,
                                V_TBL_TYPE (I).DT));
          END LOOP;
       END LOOP;
       RETURN;
    EXCEPTION
       WHEN OTHERS
       THEN
          RAISE_APPLICATION_ERROR (-20000, SQLCODE || ' ' || SQLERRM);
          RAISE;
    END;Waiting for your views.
    Regards,

    Ora Ash wrote:
    Hello Experts,
    I have created a Pipe lined function with execute immediate, due to below requirement;
    1) Columns in where clause is passed dynamically.No, that's something you've introduced, and is due to poor database design. You appear to have columns on your table called FPD1, FPD2 ... FPD31. The columns do not need to be 'passed dynamically'
    2) I want to know the data stored into above dynamic columns.And you can know the data without it being dynamic.
    3) I want to use it in report, so I don't want to insert it into a table.That's fine, though there's no reason to use a pipelined function.
    You also have an pointless exception handler, which masks any real errors.
    I'm not quite sure what the point of your "connect by" is in your query as we don't have your tables or data or know for sure what the expected output is.
    However, in terms of handling the 'dynamic' part that you've introduced, then you would be looking at doing something along the following lines, using a static query that requires no poor dynamic code, and no pipelined function...
    with x as (select level as dy from dual connect by level <= 31)
    select a.low_plan_no
          ,a.fpd
          ,a.serial_no
          ,a.cedia_code
          ,trunc(c.low_plan_period_from)+a.dy-1 as dt
    from  (select low_plan_no
                 ,dy
                 ,'FPD'||dy as fpd
                 ,spts
                 ,serial_no
                 ,cedia_code
           from (
                 select low_plan_no
                       ,x.dy
                       ,case x.dy when 1 then fpd1
                                  when 2 then fpd2
                                  when 3 then fpd3
                                  when 4 then fpd4
                                  when 5 then fpd5
                                  when 6 then fpd6
                                  when 7 then fpd7
                                  when 8 then fpd8
                                  when 9 then fpd9
                                  when 10 then fpd10
                                  when 11 then fpd11
                                  when 12 then fpd12
                                  when 13 then fpd13
                                  when 14 then fpd14
                                  when 15 then fpd15
                                  when 16 then fpd16
                                  when 17 then fpd17
                                  when 18 then fpd18
                                  when 19 then fpd19
                                  when 20 then fpd20
                                  when 21 then fpd21
                                  when 22 then fpd22
                                  when 23 then fpd23
                                  when 24 then fpd24
                                  when 25 then fpd25
                                  when 26 then fpd26
                                  when 27 then fpd27
                                  when 28 then fpd28
                                  when 29 then fpd29
                                  when 30 then fpd30
                                  when 31 then fpd31
                        else null
                        end as spts
                       ,serial_no
                       ,cedia_code
                 from   x cross join m_low_plan_details
                 where  serial_no = p_serial_no
                 and    cedia_code = p_cedia_code
                 and    low_plan_no = p_low_plan_no
           where  nvl(spts,0) > 0
          ) A
          join m_low_plan_details B on (    A.low_plan_no = B.low_plan_no
                                        and A.cedia_code = B.cedia_code
                                        and A.serial_no = B.serial_no
          join m_low_plan_mstr C on (    B.low_plan_no = C.low_plan_no
                                     and B.client_code = C.client_code
                                     and B.variant_code = C.variant_code
    connect by level <= spts;... so just remind us again why you think it needs to be dynamic?

  • Dimension table to support Hierarchy and the aggregation functions

    Hello expert,
    Now I seem to know why those aggregation functions e.g. SUM, COUNT failed whenever the report is executed.
    I have a fact table REJECT_FACT contains all the information of rejects:
    Reject ID
    Reject Category
    Reject Code
    Reject Desc
    Site Desc
    Site Code
    Region Desc
    Age Group
    Reject Date
    So I created a alias REJECT_DIM based on REJECT_FACT. After several trials, I think that the aggregation functions do not work with alias because after I remove the REJECT_DIM, the aggregation seem working.
    Is my concept right? Or I am missing something? I don't understand that the data model for datawarehouse should be simple, why do we need to create many dimension tables to support the hierarchy?

    Hello expert,
    Thank you very much for your reply.
    Actually the data model is very simple. There is only one physical table REJECT_FACT. The structure is as follows:
    Reject ID (NUMBER)
    Reject Category (VARCHAR2)
    Reject Code (VARCHAR2)
    Reject Code Desc (VARCHAR2)
    Site Desc (VARCHAR2)
    Site Code (VARCHAR2)
    Region Desc (VARCHAR2)
    Age Group (VARCHAR2)
    Reject Date (DATE)
    The hierarchy required is as follows:
    Reject Category -> Reject Code Desc -> Site Desc -> Region Desc -> Age Group -> Reject Date.
    I want to produce count on each hierachy level.
    How to populate the hierachy structure effectively?
    Thanks......

  • How to optimize a MDX aggregation functions containing "Exists"?

    I have the following calculated measure:
    sum(([D Player].[Player Name].[All],
    exists([D Match].[Match Id].children,([D Player].[Player Name].currentmember,[Measures].[In Time]),"F Player In Match Stat" ))
    ,[Measures].[Goals])
    Analyzing this calculated measure (the one with "nonempty") in MDX Studio shows "Function
    'Exists' was used inside aggregation function - this disables block computation mode".
    Mosha Pasumansky spoke about this in one of his posts titled "Optimizing
    MDX aggregation functions" where he explains how to optimize MDX aggregation functions containing "Filter",
    "NonEmpty", and "Union", but he said he didn't have time to write about Exists, CrossJoin, Descendants, or EXISTING (he posted this in Oct. 2008 and the busy man didn't have time since that date :P )... so anyone knows an article that continues
    on what Mosha miss or forgot? how to optimize a MDX aggregation function containing "Exists"? what can I do to achieve the same as this calculated measure but in block mode not cell-by-cell mode ?

    Sorry for the late replay.
    I didn't check if your last proposed solution is faster or not, but I'm sorry to say that it gave the wrong result, look at this:
    Player Name
    Players Team
    Goals Player Scored with Team
    A
    Team's Goals in Player's Played Matches
    Lionel Messi
    Argentina
    28
    28
    110
    Lionel Messi
    Barcelona
    341
    330
    978
    The correct result should be like the green column. The last proposed solution in the red column.
    If you look at the query in my first post you will find that the intention is to find the total number of goals a team scored in all matches a player participated in. So in the above example Messi scored 28 goals for Argentina (before the last world cup:)
    )  when the whole Argentinian team scored 110 goals (including Messi's goals) in those matches that Messi played even one minute in.

  • Aggregation Function

    I followed an example on the web and created a LIST() aggregation function to transpose rows to a comma delimited string. After certain length, the result appears to be out of order. I thought it was parallel_enable issue, but it's the same after I removed the clause from CREATE FUNCTION statement.
    For example, the following SQL
    SELECT LIST(column_name) FROM user_tab_columns
    WHERE table_name='TEST' ORDER BY column_id
    generate the following string:
    c122,c123,c124,...,c1,c2,c3,...,c121
    What should I do to correct this behavior? Thanks.
    Here is the script:
    create or replace type ListType as object
    (list varchar2(4000),
    static function ODCIAggregateInitialize(sctx IN OUT ListType) return number,
    member function ODCIAggregateIterate(self IN OUT ListType, value IN varchar2) return number,
    member function ODCIAggregateTerminate(self IN ListType, returnValue OUT varchar2, flags IN number) return number,
    member function ODCIAggregateMerge(self IN OUT ListType, ctx2 IN ListType) return number
    create or replace type body ListType
    is
    static function ODCIAggregateInitialize(sctx IN OUT ListType)
    return number is
    begin
    sctx := ListType(null);
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT ListType, value IN varchar2)
    return number is
    begin
    self.list := self.list || ',' || value;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN ListType, returnValue OUT varchar2, flags IN number)
    return number is
    begin
    returnValue := rtrim(ltrim(self.list,','),',');
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT ListType, ctx2 IN ListType)
    return number is
    begin
    self.list := self.list|| ',' || ctx2.list;
    return ODCIConst.Success;
    end;
    end;
    create or replace function list(input varchar2) return varchar2
    parallel_enable aggregate using ListType;
    grant EXECUTE on list to PUBLIC
    /

    in 10g, you could use something like
    regexp_replace( list(distinct to_char(column_id,'0000')||':'||column_name), '([:[digit]:]){4}:')
    if you need to support 9i, you cannot use regular expression, but you can write your own function and concatenated substr. kind of loop with instr(:) and substr()
    HTH
    Laurent
    Message was edited by:
    Laurent Schneider
    but, if you need to sort, use ORDER BY. my solution is a not recommended, it is a very dirty trick
    Message was edited by:
    Laurent Schneider
    use order by within your aggregate function, to sort the resultset each time, as advised by tom kyte in the link above

  • User Aggregated Function in Discoverer

    Hi.
    I'm trying to use an "User Aggregated Function" in Discoverer. This function concatenates a varchar field, and I want to use as a max(), min() or count() functions, but Discoverer always write this function in the group block of the query, and the databse generates an error.
    This is the user agrgegated function:
    CREATE OR REPLACE function DDS_UXXIINV.var_agg (input varchar2) return varchar2
    parallel_enable aggregate using agg_t;
    The package agg_t is defined as:
    create or replace type agg_t as object (
    str_agg varchar2(4000),
    static function ODCIAggregateInitialize(sctx in out agg_t)
    return number,
    member function ODCIAggregateIterate (self in out agg_t,
    value in varchar2 )
    return number,
    member function ODCIAggregateTerminate (self in agg_t ,
    return_value out varchar2,
    flags in number )
    return number,
    member function ODCIAggregateMerge(self in out agg_t,
    ctx2 in agg_t )
    return number
    create or replace type body agg_t is
    static function ODCIAggregateInitialize(sctx in out agg_t)
    return number is
    begin
    sctx := agg_t(null);
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(
    self in out agg_t, value in varchar2)
    return number is
    begin
    str_agg := str_agg || value;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self in agg_t,
    return_value out varchar2, flags in number) return number is
    begin
    return_value := str_agg;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self in out agg_t,
    ctx2 in agg_t) return number is
    begin
    str_agg := str_agg || ctx2.str_agg;
    return ODCIConst.Success;
    end;
    end;
    When I use this functions (as a calculated field) Discoverer generates this statment:
    select var_agg(field1), field2 form table group by var_agg(field1), field2;
    I want this statement:
    select var_agg(field1), field2 form table group by field2;
    Sometimes Oracle generates a error messages saying that there's a wrong combinations of joins (translated from spainsh)
    Regards
    Óscar Blanco

    Hi,
    Unfortunately, you cannot import user defined group functions into Discoverer, Discoverer does not understand them.
    Rod West

  • Return multiple columns from an analytic function with a window

    Hello,
    Is it possible to obtain multiple columns from an analytic function with a window?
    I have a table with 4 columns, an id, a test id, a date, and the result of a test. I'm using an analytic function to obtain, for each row, the current test value, and the maximum test value in the next 2 days like so:
    select
    id,
    test_id,
    date,
    result,
    MAX ( result ) over ( partition BY id, test_id order by date RANGE BETWEEN CURRENT ROW AND INTERVAL '2' DAY FOLLOWING ) AS max_result_next_two_day
    from table
    This is working fine, but I would like to also obtain the date when the max result occurs. I can see that this would be possible using a self join, but I'd like to know if there is a better way? I cannot use the FIRST_VALUE aggregate function and order by result, because the window function needs to be ordered by the date.
    It would be a great help if you could provide any pointers/suggestions.
    Thanks,
    Dan
    http://danieljamesscott.org

    Assuming RESULT is a positive integer that has a maximum width of, say 10,
    and assuming date has no time-component:
    select
       id
      ,test_id
      ,date
      ,result
      ,to_number(substr(max_result_with_date,1,10)) as max_result_next_two_day
      ,to_date(substr(max_result_with_date,11),'YYYYMMDD') as date_where_max_result_occurs
    from (select
            id
           ,test_id
           ,date
           ,result
           ,MAX(lpad(to_char(result),10,'0')||to_char(date,'YYYYMMDD'))
               over (partition BY id, test_id
                     order by date
                     RANGE BETWEEN CURRENT ROW AND INTERVAL '2' DAY FOLLOWING )
            AS max_result_with_date
          from table)

Maybe you are looking for

  • Error while generating CHM from Framemaker 7.2 using Quadralay webworks 7

    Hi, Iam using FrameMaker 7.2 and Quadralay WebWorks 7.0 for generating CHM files. While creating the webworks project I get error: "The Wizard was unable to scan documents". The support / information for this error suggests modifying the maker.ini fi

  • Just starting out with calculations between fields

    I'd like to to include some text fields where numbers are entered, then a button is pressed, and the mathematical results of the fields are displayed. In Adobe Acrobat Pro 9 I opened Forms ... Start Form Wizard, and placed all the elements - three Nu

  • ITunes cannot run because it detects a problem with Quicktime

    When I click on the help icon I am prompted to uninstill Quicktime. The problem is, Quicktime isn't in the list of installed programs. It is visable if I go to classic view in the control panel page but I can't seem to delete it. Any help would be gr

  • I keep getting error message"

    i keep getting error message " selected items can't be edited in iPhoto" . the video is from my iPhone and have edited others but this one has me stumped. it will let me add music and a text tile , but i want the advanced edit. any ideas? thanks

  • Auto delete trash in mail

    How can I set an auto delete for trash in mavericks mail after either 2 months or 6 months? thanks Marianne