Re:groupby clause

Hi all,
Can any one explain what is the exact use of Group by clause in the select statement .
regards,
Sasi

The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns. The GROUP BY concept is one of the most complicated concepts for people new to the SQL language and the easiest way to understand it, is by example.
We want to retrieve a list with unique customers from our Sales table, and at the same time to get the total amount each customer has spent in our store.
OrderID OrderDate OrderPrice OrderQuantity CustomerName
1 12/22/2005 160 2 Smith
2 08/10/2005 190 2 Johnson
3 07/13/2005 500 5 Baldwin
4 07/15/2005 420 2 Smith
5 12/22/2005 1000 4 Wood
6 10/2/2005 820 4 Smith
7 11/03/2005 2000 2 Baldwin
You already know how to retrieve a list with unique customer using the DISTINCT keyword:
SELECT DISTINCT CustomerName FROM Sales
The SQL statement above works just fine, but it doesn’t return the total amount of money spent for each of the customers. In order to accomplish that we will use both SUM SQL function and the GROUP BY clause:
SELECT CustomerName, SUM(OrderPrice) FROM Sales
GROUP BY CustomerName
We have 2 columns specified in our SELECT list – CustomerName and SUM(OrderPrice). The problem is that SUM(OrderPrice), returns a single value, while we have many customers in our Sales table. The GROUP BY clause comes to the rescue, specifying that the SUM function has to be executed for each unique CustomerName value. In this case the GROUP BY clause acts similar to DISTINCT statement, but for the purpose of using it along with SQL aggregate functions. The result set retrieved from the statement above will look like this
CustomerName OrderPrice
Baldwin 2500
Johnson 190
Smith 1400
Wood 1000
You do grouping using GROUP BY by more than one column, for example:
SELECT CustomerName, OrderDate, SUM(OrderPrice) FROM Sales
GROUP BY CustomerName, OrderDate
When grouping, keep in mind that all columns that appear in your SELECT column list, that are not aggregated (used along with one of the SQL aggregate functions), have to appear in the GROUP BY clause too.

Similar Messages

  • Selecting top x rows for each of the groupby clause

    Hi Gurus (again).
    I have this query to select the top 24 rows:
    select * from
    +(+
    select proid, to_char((next_day(trunc(request_date, 'iw'), 'mon')-7), 'YYYY') as YEAR, to_char(request_date, 'IW') as WEEK,
    next_day(trunc(request_date, 'iw'), 'mon')-7 as weekdate,
    trunc(avg(case when report_date > request_date then ((report_date - request_date) * 24) end),1) as avg_ERT_hr,  '24' as ERT_goal,
    trunc(avg(case when response_date > request_date then ((response_date - request_date) * 24) end),1) as avg_IRT_hr,  '48' as IRT_goal,
    trunc(avg(case when deliver_date > request_date then ((deliver_date - request_date)) end),1) as avg_IDT_day,  '0' as IDT_goal,
    trunc(avg(case when complete_date > request_date then ((complete_date - request_date)) end),1) as avg_ORT_day,  '0' as ORT_goal
    from biw_hda_event
    where request_date is not null
    group by proid, to_char((next_day(trunc(request_date, 'iw'), 'mon')-7), 'YYYY'), to_char(request_date, 'IW'), next_day(trunc(request_date, 'IW'), 'MON')-7
    order by 1 desc, 2 desc
    +) where rownum <=24+
    The problem here is that I have a group by "proid" clause in addition to the dates. My purpose is to be able to select the top 24 rows for each of the "proid" that is already grouped by the date. Essentially, the top 24 is the last 24 weeks pertaining to that "proid". How can I do this effectively without creating heaps of UNION clause for each of the "proid"?
    thanks in advance

    I meant to delete this thread, but I do not know how to. Sorry.

  • GROUPBY error in OBIEE 10g

    I had a requirment where I need to calculate the duration of the etl runs on daily basis
    So I have calculated the duration using the below formula.
    by grouping the run_wid and using the column in criteria and hiding it(in order to avoid the error 'column in GROUPBY clause not in the projection list.')..
    the reason for grouping the run_wid is when the etl fails it is run multiple times and multiple entries on same run_wid are generated so I have captured them by
    grouping them based on run_wid.
    Everything works here fine.
    But when I want to analyze on the whole year average etl runs using the above process.
    So in order to achieve this by taking the year and duration and grouping by run_wid. I again get the error 'column in GROUPBY clause not in the projection list.').
    I can't use the run_wid in the criteria because it not showing at year level. Please suggest a way/idea on achieving this.
    Edited by: 949675 on May 30, 2013 10:17 PM

    Hi Yadav,
    Thanks for suggesting the idea it worked little bit by not making me to pull the run_wid in both
    criteria and adding in GROUP by in advanced tab.
    The problem what I am facing now is the value is not average values and its only showing the sum
    of all the values
    The formula for calculating Average is Avg(round(sum(TimestampDiff(SQL_TSI_SECOND,Audit."Start Time",Audit."End Time"))/60,2)/60 by run_wid)
    The columns in my criteria are
    Year|Average
    Ex:
    In year 2011 the ETL has run 50 times, I am seeing 50 etls total run time in Average.

  • Oracle report parameters- please help

    iam working on reports 2.5 and oracle DB7.3.
    In a report parameter in order to retrive the parameters i gave
    a query as
    select docno from docket where status='A'
    for some period it has worked well.
    may be as the number of transactions have increased the report
    parameter form is not gettign loaded and when i click the report
    it gives me r25srv error.
    i could get rid of this error by restricting the parameters
    pertaining only to 2001 documents.
    the report is working but i have limited the trasactions here
    and the problem has been solved temporarily.
    my question is
    1) does the parameter field takes limited no of transactions.?
    if so what is limit to the parmeters.
    this i am asking the reason is i found some docnos got displayed
    latter i could view only junck characters in the parameter drop
    down list. This could view only once.all the time it gives
    r25srv error
    2) how can i retrive all the docnos in the parameter other than
    the above query.
    please help me

    hello Thiru
    thank u for ur help.
    here i donot find necessity of using Distinct and groupby clause.
    as the docnos are unique in the table i was referring,further
    iam not using any function so as to use groupby clause.
    Ofcourse i will try with LOV by calling reports from forms.
    This particular table contains 12000 records ,each record has 1
    doc no assigned to it.That means i want all the 12000 docs to be
    viewed in the parameter so that i can select one doc no to view
    that particular report.
    regards

  • Oracle Report Manager - Please help

    Just a quick question for anyone familiar with this product. We have Oracle Applications/Financials 16.1, 10.7 SC and run on DG-UX. It looks like Report Manager is only available for NT and Solaris.... will the Solaris version work on the DG-UX platform as well?
    Thanks in advance,
    Darius

    hello Thiru
    thank u for ur help.
    here i donot find necessity of using Distinct and groupby clause.
    as the docnos are unique in the table i was referring,further
    iam not using any function so as to use groupby clause.
    Ofcourse i will try with LOV by calling reports from forms.
    This particular table contains 12000 records ,each record has 1
    doc no assigned to it.That means i want all the 12000 docs to be
    viewed in the parameter so that i can select one doc no to view
    that particular report.
    regards

  • Materialized View creation with REFRESH FAST

    Hello ,
    Please see below case,
    TABLE A1(partitioned range+list)
    COLUMN C1  -- Primary key
    COLUMN C2  -- NUMBER
    TABLE D1
    COLUMN C1 -- PRIMARY KEY
    created MV log as below
    CREATE MATERIALIzED VIEW LOG ON A1 WITH ROWID,PRIMARY KEY INCLUDING NEW VALUES;
    CREATE MATERIALIzED VIEW LOG ON D1 WITH ROWID,PRIMARY KEY INCLUDING NEW VALUES;
    Trying to create MV like below:
    CREATE MATERILIZED VIEW mv1test
                                    REFRESH FAST ON COMMIT
    AS
    Select
    FROM A1,
                            D1
                    WHERE A1.C1 = D1.CI
    AND A1.C2 IS NOT NULL;
    It gives below error message:
    ORA-12052: cannot fast refresh materialized view schema.mv1test
    12052. 00000 -  "cannot fast refresh materialized view %s.%s"
    *Cause:    Either ROWIDs of certain tables were missing in the definition or
               the inner table of an outer join did not have UNIQUE constraints on
               join columns.
    *Action:   Specify the FORCE or COMPLETE option. If this error is got
               during creation, the materialized view definition may have be
               changed. Refer to the documentation on materialized views.
    However ,as discussed in earlier thread i checked all general restrictions of the 'Refresh fast' approach for join.
    Restrictions on Fast Refresh on Materialized Views with Joins Only
    Defining queries for materialized views with joins only and no aggregates have the following restrictions on fast refresh:
    1) They cannot have GROUPBY clauses or aggregates.
    2) Rowids of all the tables in the FROM list must appear in the SELECT list of the query.
    3)Materialized view logs must exist with rowids for all the base tables in the FROM list of the query.
    4)You cannot create a fast refreshable materialized view from multiple tables with simple joins that include an object type column in the SELECTstatement.
    As per above restrictions ,
    1) Group by clause is not present
    2)i do not understand 2nd point , i have added a1.rowid  and d1.rowid in  select statement of MV, but got same error.
    3) observed same as 2nd point.
    4)we have CLOB column in select list. Tried removing this column but got same error.
    Please do let me know any workaround on this.
    Thanks in advanced ..
    PM

    Basic Materialized Views show how to analyse MVs using dbms_mview. I'm not sure about creating MVs on partitioned tables, that partition maintenance might cause problems

  • Polling issues

    Hi All,
    Is there any limitation of specifying the query type in polling process?
    Suppose I have two tables RESOURCESID, resourceId, modified_date, polling_flag and USERSID, userId, user_info. No relationship is defined between tables in database.
    .And I want query something like this...
    SELECT R.ID, R.modified_date, U.user_info from RESOURCES R, USERS U WHERE R.resourceId=U.userId and R.ID in http://.... some other query having groupby clause
    Can I do that? If yes then how and if no then what is the alternate for this.
    Thanks.

    I want to create a query like the below type
    SELECT opportunity_id, OPP_LAST_MODIFIED_DT FROM sf_opportunity_INTF A
    WHERE OPP_LAST_MODIFIED_DT > (sysdate-1) and isprocessed ='N'
    and OPP_LAST_MODIFIED_DT = (SELECT max(OPP_LAST_MODIFIED_DT) FROM sf_opportunity_INTF B
    WHERE B.opportunity_id = A.opportunity_id and B.isprocessed = A.isprocessed)
    This query may be incorrect. But I want something like this.

  • Sequence number not allowed

    Sequence Pseudocolumns
    See restrictions on sequences. 
    Restrictions on Sequence Values You cannot use CURRVAL and NEXTVAL in the following constructs:
    A subquery in a DELETE, SELECT, or UPDATE statement
    A query of a view or of a materialized view
    A SELECT statement with the DISTINCT operator
    A SELECT statement with a GROUPBY clause or ORDERBY clause
    A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator
    The WHERE clause of a SELECT statement
    The DEFAULT value of a column in a CREATETABLE or ALTERTABLE statement
    The condition of a CHECK constraint
    Which rule am I breaking here, is there an implied GROUP BY as Im using the aggregate function even though its not specified?
    create table t10
    (col1  number,
    col2 number);
    insert into t10
    values (null,1);
    insert into t10
    values (null,2);
    create sequence s_test;
    select s_test.nextval from dual;
    1
    select nvl(sum(col1),999) from t10;
    NVL(SUM(COL1),999)
                   999
    select nvl(sum(col1), s_test.nextval) from t10
    ERROR at line 1:
    ORA-02287: sequence number not allowed here

    Docs can have bugs, yes. That wouldn't be the first time.
    It could be very tedious to give all and every cases where nextval should not work, I'm sure there're other cases.
    Well, unless you have plenty time to spend solving the docs problems, you may want to rewrite your code to make it work. Much easier, and mush faster than going through the support to know which is right between doc and Oracle code. I'd tend to think about the 2nd though, since we are talking about an aggregate.
    What about :
    select nvl(mysum, s_test.nextval) from (select sum(col1) mysum from t10);
    Nicolas.

  • SPGridView group duplication issue

    Hi all,
    i am facing the issue while developing the webpart. i am using SPGridview and creating groups in spgridview. as shown below in the image. 2 group showing with same name. could any buddy tell me what is the issue with this code.
    <SharePoint:SPGridView runat="server" ID="grdSearchResults" width="50%" AutoGenerateColumns="False" EnableViewState="false" AllowSorting="true" AllowGrouping="true" GroupField="ApplicationStatus"
    AllowGroupCollapse="true" AllowFiltering="true" FilterDataFields="ApplicationStatus"
                    PageSize="15"  AllowPaging="True" CellPadding="4" CellSpacing="0" OnPageIndexChanging="grdSearchResults_PageIndexChanging" OnSorting="grdSearchResults_Sorting"
    OnRowDataBound="grdSearchResults_RowDataBound" OnRowCreated="grdSearchResults_RowCreated" OnSelectedIndexChanged="grdSearchResults_SelectedIndexChanged"> 
                    <HeaderStyle Wrap="false" />
                    <AlternatingRowStyle CssClass="GridAlternativeStyle" />
                        <Columns>
                        <asp:TemplateField HeaderText="Details">
                        <ItemTemplate>
                        <asp:HyperLink ID="hypDetailLink" onclick=<%# "javascript:openDialog('" + Eval("TrackNo") + "')" %> runat="server"><div
    class="comntImgStyleDetails"></div></asp:HyperLink>
                        </ItemTemplate>
                        </asp:TemplateField>                   
                        <asp:BoundField DataField="Title" HeaderText="Name"></asp:BoundField>
                        <asp:BoundField DataField="TrackNo" HeaderText="Track No"  />
                        <asp:BoundField DataField="Gender" HeaderText="Gender"  />
                        <asp:BoundField DataField="DateOfBirth" HeaderText="Date Of Birth" />
                        <asp:BoundField DataField="Qualification" HeaderText="Qualification"  SortExpression="Qualification"  />
                        <asp:BoundField DataField="Major" HeaderText="Major" SortExpression="Major" />
                        <asp:BoundField DataField="Minor" HeaderText="Minor" SortExpression="Minor" />
                        <asp:BoundField DataField="Nationality" HeaderText="Nationality" SortExpression="Nationality" />
                        <asp:BoundField DataField="ExpectedSalary" HeaderText="From Salary" SortExpression="ExpectedSalary" />
                        <asp:BoundField DataField="ToSalary" HeaderText="To Salary" SortExpression="ToSalary" />
                        <asp:BoundField DataField="ApplicationStatus" HeaderText="Application Status" SortExpression="ApplicationStatus" />
                        </Columns> 
                    <EmptyDataRowStyle CssClass="GridViewItem" />
                    <EmptyDataTemplate>
                    <asp:Label ID="lblNoRecordsFound" runat="Server" Text="No Records Found"></asp:Label>
                    </EmptyDataTemplate>
                    <HeaderStyle CssClass="GridHeader" />
                    <PagerSettings FirstPageText="First" LastPageText="Last" />
                    <PagerStyle CssClass="PagerStyle"/>
                    <RowStyle CssClass="RowStyle" />
                    </SharePoint:SPGridView>
    BestRegards|SharePoint Techies

    Hello Briji,
    Thank you very much for your reply, basically I am using search API and ApplicationStatus is a manage property. Here is the sample code that I have used. But I have also tried caml query using groupby clause
    and it's working fine. Is there any way to use groupby clause in keywordquery. Because if use groupby cluase in this code so that can resolve the issue.
    var kwq = new KeywordQuery(Site);
    kwq.QueryText = string.Format("Title:\"{0}\"", keywords); kwq.ResultTypes = ResultType.RelevantResults; kwq.RowLimit = pageSize;
    kwq.StartRow = startRow;
    kwq.TrimDuplicates = true;
    kwq.HiddenConstraints = "path:\"*/User Docs*\" AND IsDocument:true";
    kwq.KeywordInclusion = KeywordInclusion.AllKeywords;
    kwq.SelectProperties.Add("ApplicationStatus");
    kwq.SelectProperties.Add("ContentClass");
    kwq.SelectProperties.Add("IsDocument");
    // Custom (they come back blank even when set as managed properties) kwq.SelectProperties.Add("IntroText");
    kwq.SelectProperties.Add("Date");
    Thanks Regards Wasi
    BestRegards|SharePoint Techies

  • Using round off function in where clause

    Hi All,
    I'm trying to use round off function in where clause, I seek help in completing this script.
    WITH CR_Details AS
    (Select
    request_id,
    parent_request_id,
    fcpt.user_concurrent_program_name Request_Name, phase_code, status_code,
    round((fcr.actual_completion_date - fcr.actual_start_date),3) * 24 * 60 as Run_Time,
    round(avg(round(to_number(actual_start_date - fcr.requested_start_date),3) * 1440),2) wait_time,
    fu.User_Name Requestor,
    fcr.argument_text parameters,
    to_char (fcr.requested_start_date, 'MM/DD HH24:mi:SS') requested_start,
    to_char(actual_start_date, 'MM/DD/YY HH24:mi:SS') ACT_START,
    to_char(actual_completion_date, 'MM/DD/YY HH24:mi:SS') ACT_COMP,
    fcr.completion_text
    From
    apps.fnd_concurrent_requests fcr,
    apps.fnd_concurrent_programs fcp,
    apps.fnd_concurrent_programs_tl fcpt,
    apps.fnd_user fu
    Where 1=1
    and fcr.concurrent_program_id = fcp.concurrent_program_id
    and fcp.concurrent_program_id = fcpt.concurrent_program_id
    and fcr.program_application_id = fcp.application_id
    and fcp.application_id = fcpt.application_id
    and fcr.requested_by = fu.user_id
    and fcpt.language = 'US'
    and fcr.actual_start_date like sysdate )
         select crd.*
         from CR_Details crd
         where Run_time <> '0'
         AND wait_time <> '0'
    GROUP BY
    crd.request_id,
    crd.parent_request_id,
    crd.fcpt.user_concurrent_program_name,
    crd.requested_start_date,
    crd.User_Name,
    crd.argument_text,
    crd.actual_completion_date,
    crd.actual_start_date,
    crd.phase_code,
    crd.status_code,
    crd.resubmit_interval,
    crd.completion_text,
    crd.resubmit_interval,
    crd.resubmit_interval_unit_code,
    crd.description
    Not sure about the GROUPBY function referencing the "crd." .

    Hi,
    The best thing for you to do is start over. Start as small as possible, then take baby steps.
    Pick one of the tables; fcr perhaps, and write a query that just uses that table, like this:
    SELECT    *
    FROM       apps.fnd_concurrent_requests     fcr
    WHERE       fcr.actual_start_date          >= TRUNC (SYSDATE)
    AND       fcr.actual_start_dt          <  TRUNC (SYSDATE) + 1
    ;(I think this is what you meant to do when you said "... LIKE SYSDATE".)
    Make sure this little query gets credible results. When that tiny query is working perfectly, add another line or two. You can cut and paste code from what you posted, if that helps you.
    If you get stuck, post the last version of your code that worked perfectly, and the latest version (only a line or two bigger) that has the problem. Describe what the problem is. If you get an error, post the complete error message. In any event, post CREATE TABLE and INSERT statements for all the tables and columns needed to run the query, and the results you want to get from that query.
    When you post any code, format it, so that how the code looks on the screen gives some clues about how it is working.
    When you post any formatted text on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    If you going to use the AVG function in the sub-query, then you probably need to do a GROUP BY in the sub-query.
    If you're not using any aggregate functions (like AVG) in the main query, then you probably don't want to do a GROUP BY in the main query.
    I know this is a lot of work.  I'm sorry.  If there was an easier way, I wouldn't ask you to do all this.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Query Plan 'group-by' clause

    In evaluating several query plans, I've discovered several sqlstop messages that read:
    <groupBy preclustered="true" sqlstop="Cannot generate SQL for the 'group-by' clause because it is not equivalent to the relational GROUP BY clause" stable="true">
    I've examined the XQuery code and find no group clause and I can't find a reference to this message in the documentation or by googling the text. I assume that the grouping is being done implicitly by ODSI since it is not in the XQuery source. I have tried restructuring the code to no avail.
    My question is -- is this causing me a performance problem since the sql is not generated, and if so, what steps must I take in the xquery structure to avoid this issue.
    Many thanks to anyone who can provide some insight into this.
    Regards,
    PB

    is this causing me a performance problem since the sql is not generatedMy question is - why are you asking this question? :) Do you have a performance problem? The "Best Practices" posted as an announcement in this forum might help. Otherwise engage customer support.
    To answer your question - your xquery likely generates nested/hierarchical xml - and looks something like below - which can be implemented with a sql left-outer-join ordered by CUSTOMER_ID of the customer-table, and taking the rows returned and ... grouping by CUSTOMER_ID to eliminate the duplicate customer information. So there's your group-by. But you cannot write sql that has a left-outer join, and then a group-by on the left-hand side. So the group by is done in the engine. Since the results are already sorted, the group-by in the engine simply skips over the duplicates (i.e. it's basically free).
    for $c in CUSTOMER()
    where $c/LAST_NAME = $lastname
    return
    <CUSTOMER>
    ... $c/CUSTOMER_ID ... (: in a left-outer-join, the CUSTOMER_ID is duplicated for every ORDER :)
    { for $o in ORDER()
    where $o/CUSTOMER_ID eq $c/CUSTOMER_ID
    return
    </CUSTOMER>

  • Passing where and group by clause to cursor

    I am working on a procedure that builds a where clause and needs a group by clause to return the correct results. I am trying to pass both the where and group by variables into the cursor.
    The variables are getting populated correctly, but when the cursor gets created, the variables are not in the cursor.
    Here is the code I'm working with. It is a part of a package, but makes no calls to other parts of the package.
    PROCEDURE createFollowUpTask_Exposure( psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE default NULL,
    psAlarmtyp IN tis.tial.alarmtyp%TYPE default NULL,
    psSubtyp IN tis.tial.subtyp%TYPE default NULL,
    pnDays IN NUMBER default NULL,
    psKampkod IN tis.tiin.kampkod%TYPE default NULL,
    psKatnr IN tis.tiin.katnr%TYPE default NULL,
    psUtgava IN tis.tiin.utgava%TYPE default NULL,
    psKatslag IN tis.tikg.katslag%TYPE default NULL,
    psProdsyst IN tis.tikg.prodsyst%TYPE default NULL,
    psUppgtyp IN tis.tiin.uppgtyp%TYPE default NULL,
    psProdkod IN tis.tiin.prodkod%TYPE default NULL,
    psStatus IN tis.tiin.status%TYPE default NULL
    ) AS
    cTIAL tis.tial%ROWTYPE;
    vLopnr tis.tial.lopnr%TYPE;
    vSqlWhere VARCHAR2(4000);
    vGroupBy VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
    cSelectCursor SYS_REFCURSOR;
    vSqlSelect VARCHAR2(4000);
    psDays VARCHAR2(50);
    cRec T_TIAL_REC;
    nCount number := 0;
    CURSOR cSqlSelect( SqlWhere IN VARCHAR2, GroupBy IN VARCHAR2) IS
    SELECT tiin.kampkod, tiin.abnr, tiko.fordsalj, MAX(tici.regdat) ALARMDATE
    FROM tis.tiin
    JOIN tis.tiko ON tiin.kampkod = tiko.kampkod AND tiin.abnr = tiko.abnr
    JOIN core.tici ON tiin.kampkod = tici.kampkod AND tiin.abnr = tici.abnr AND tici.inplnr = tiin.inplnr
    WHERE 1=1 || SqlWhere
    GROUP BY GroupBy;
    BEGIN
    -- If these parameters are null, raise error
    IF psUppgkedjetyp IS NULL and psSubtyp IS NULL THEN
    raise_application_error(-20001,
    'Either Event Chain or Starting Event must be assigned');
    END IF;
    -- Populate TIAL values
    IF psUppgkedjetyp IS NOT NULL THEN
    cTIAL.Uppgkedjetyp := psUppgkedjetyp;
    END IF;
    IF psAlarmtyp IS NOT NULL THEN
    cTIAL.Alarmtyp := psAlarmtyp;
    END IF;
    cTIAL.Handklass := 'T';
    cTIAL.Blobid := 0;
    IF pnDays IS NOT NULL THEN
    psDays := '+ '||pnDays;
    END IF;
    IF psSubtyp IS NOT NULL THEN
    cTIAL.Subtyp := psSubtyp;
    END IF;
    -- Create Where clause for cursor
    vSqlWhere := '';
    IF psKampkod IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.kampkod = '''|| psKampkod||'''';
    END IF;
    IF psKatnr IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.katnr = '''||psKatnr||'''';
    END IF;
    IF psUtgava IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.utgava = '''||psUtgava||'''' ;
    END IF;
    IF psKatslag IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tikg.katslag = '''||psKatslag||'''';
    END IF;
    IF psProdsyst IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tikg.prodsyst = '''||psProdsyst||'''';
    END IF;
    IF psUppgtyp IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.uppgtyp = '''||psUppgtyp||'''';
    END IF;
    IF psProdkod IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.prodkod = '''||psProdkod||'''';
    END IF;
    IF psStatus IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.status = '''||psStatus||'''';
    END IF;
    -- Loop through all records meeting input parameters and set required TIAL values.
    FOR i IN cSqlSelect(vSqlWhere, vGroupBy)
    LOOP
    --FETCH cSelectCursor INTO cRec;             
    cTIAL.Kampkod := '';
    cTIAL.Abnr := '';
    cTIAL.Sign := '';
    cTIAL.Alarmdate := '';
    cTIAL.Kampkod := i.Kampkod;
    cTIAL.Abnr := i.Abnr;
    cTIAL.Sign := i.fordsalj;
    cTIAL.Alarmdate := i.alarmdate;
    nCount := nCount + 1;
    IF vLopnr = -1 THEN
    raise_application_error(-20002,
    'Error Creating task for: '||cTIAL.Kampkod||' '||cTIAL.Abnr||' Sales Rep: '||cTIAL.Alarmdate);
    END IF;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('I created '||nCount||' records.');
    END createFollowUpTask_Exposure;
    Thanks in advance for any help.

    Hi,
    Welcome to the forum!
    Try this (not tested) as an example:
    PROCEDURE createFollowUpTask_Exposure(psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE DEFAULT NULL,
                                          psAlarmtyp     IN tis.tial.alarmtyp%TYPE DEFAULT NULL,
                                          psSubtyp       IN tis.tial.subtyp%TYPE DEFAULT NULL,
                                          pnDays         IN NUMBER DEFAULT NULL,
                                          psKampkod      IN tis.tiin.kampkod%TYPE DEFAULT NULL,
                                          psKatnr        IN tis.tiin.katnr%TYPE DEFAULT NULL,
                                          psUtgava       IN tis.tiin.utgava%TYPE DEFAULT NULL,
                                          psKatslag      IN tis.tikg.katslag%TYPE DEFAULT NULL,
                                          psProdsyst     IN tis.tikg.prodsyst%TYPE DEFAULT NULL,
                                          psUppgtyp      IN tis.tiin.uppgtyp%TYPE DEFAULT NULL,
                                          psProdkod      IN tis.tiin.prodkod%TYPE DEFAULT NULL,
                                          psStatus       IN tis.tiin.status%TYPE DEFAULT NULL) AS
       cTIAL         tis.tial%ROWTYPE;
       vLopnr        tis.tial.lopnr%TYPE;
       vSqlWhere     VARCHAR2(4000);
       vGroupBy      VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
       cSelectCursor SYS_REFCURSOR;
       vSqlSelect    VARCHAR2(4000);
       psDays        VARCHAR2(50);
       cRec          T_TIAL_REC;
       nCount        NUMBER := 0;
       FUNCTION fnc_cSqlSelect(SqlWhere IN VARCHAR2,
                               GroupBy  IN VARCHAR2) RETURN VARCHAR2 IS
       BEGIN
          RETURN 'SELECT tiin.kampkod,
                 tiin.abnr,
                 tiko.fordsalj,
                 MAX(tici.regdat) ALARMDATE
            FROM tis.tiin
            JOIN tis.tiko ON tiin.kampkod = tiko.kampkod
                         AND tiin.abnr = tiko.abnr
            JOIN core.tici ON tiin.kampkod = tici.kampkod
                          AND tiin.abnr = tici.abnr
                          AND tici.inplnr = tiin.inplnr
           WHERE 1 = 1 ' || SqlWhere || ' GROUP BY ' || GroupBy;
       END fnc_cSqlSelect;
    BEGIN
       -- If these parameters are null, raise error
       IF psUppgkedjetyp IS NULL AND psSubtyp IS NULL THEN
          raise_application_error(-20001,
                                  'Either Event Chain or Starting Event must be assigned');
       END IF;
       -- Populate TIAL values
       IF psUppgkedjetyp IS NOT NULL THEN
          cTIAL.Uppgkedjetyp := psUppgkedjetyp;
       END IF;
       IF psAlarmtyp IS NOT NULL THEN
          cTIAL.Alarmtyp := psAlarmtyp;
       END IF;
       cTIAL.Handklass := 'T';
       cTIAL.Blobid    := 0;
       IF pnDays IS NOT NULL THEN
          psDays := '+ ' || pnDays;
       END IF;
       IF psSubtyp IS NOT NULL THEN
          cTIAL.Subtyp := psSubtyp;
       END IF;
       -- Create Where clause for cursor
       vSqlWhere := '';
       IF psKampkod IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.kampkod = ''' || psKampkod || '''';
       END IF;
       IF psKatnr IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.katnr = ''' || psKatnr || '''';
       END IF;
       IF psUtgava IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.utgava = ''' || psUtgava || '''';
       END IF;
       IF psKatslag IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tikg.katslag = ''' || psKatslag || '''';
       END IF;
       IF psProdsyst IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tikg.prodsyst = ''' || psProdsyst || '''';
       END IF;
       IF psUppgtyp IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.uppgtyp = ''' || psUppgtyp || '''';
       END IF;
       IF psProdkod IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.prodkod = ''' || psProdkod || '''';
       END IF;
       IF psStatus IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.status = ''' || psStatus || '''';
       END IF;ç
       -- Loop through all records meeting input parameters and set required TIAL values.
       OPEN cSelectCursor FOR fnc_cSqlSelect(vSqlWhere,
                                             vGroupBy);
       LOOP
          FETCH cSelectCursor
             INTO v; -- You must define a variable 'v' to hold the data of cursor
          EXIT WHEN cSelectCursor%NOTFOUND;
          --FETCH cSelectCursor INTO cRec;
          cTIAL.Kampkod   := '';
          cTIAL.Abnr      := '';
          cTIAL.Sign      := '';
          cTIAL.Alarmdate := '';
          cTIAL.Kampkod   := i.Kampkod;
          cTIAL.Abnr      := i.Abnr;
          cTIAL.Sign      := i.fordsalj;
          cTIAL.Alarmdate := i.alarmdate;
          nCount := nCount + 1;
          IF vLopnr = -1 THEN
             raise_application_error(-20002,
                                     'Error Creating task for: ' || cTIAL.Kampkod || ' ' ||
                                     cTIAL.Abnr || ' Sales Rep: ' || cTIAL.Alarmdate);
          END IF;
       END LOOP;
       CLOSE cSelectCursor;
       DBMS_OUTPUT.PUT_LINE('I created ' || nCount || ' records.');
    END createFollowUpTask_Exposure;
    /Regards,

  • HOW TO ADD GROUP BY CLAUSE WHEN USING Jbo:Datatable

    Would like to know if there are any provisions for adding a Group by clause so the data shown using DataTable Component cn be grouped.
    eg:
    Currently using DataTable component shows data as shown below.
    Dept Name
    10 ABC
    10 DEF
    10 PQR
    20 XYZ
    20 QQQ
    Can this be done as shown bewlow
    Dept Name
    10 ABC
    DEF
    PQR
    20 XYZ
    QQQ
    Thanks

    Hi Sashi,
    For a bc4j view object, the shape of the result set needs to be consistent. So, there can not be a groupby directly in the result set.
    However, that does not prevent you from inserting a calculated column that performs a similar calculation.
    Another mechanism might be to consider a master detail arrangement of the views where the master contains an aggregation of data from its children. You are then free to access and display this data as you choose.
    Hope this helps,
    Pete

  • Avoiding null and duplicate values using model clause

    Hi,
    I am trying to use model clause to get comma seperated list of data : following is the scenario:
    testuser>select * from test1;
    ID VALUE
    1 Value1
    2 Value2
    3 Value3
    4 Value4
    5 Value4
    6
    7 value5
    8
    8 rows selected.
    the query I have is:
    testuser>with src as (
    2 select distinct id,value
    3 from test1
    4 ),
    5 t as (
    6 select distinct substr(value,2) value
    7 from src
    8 model
    9 ignore nav
    10 dimension by (id)
    11 measures (cast(value as varchar2(100)) value)
    12 rules
    13 (
    14 value[any] order by id =
    15 value[cv()-1] || ',' || value[cv()]
    16 )
    17 )
    18 select max(value) oneline
    19 from t;
    ONELINE
    Value1,Value2,Value3,Value4,Value4,,value5,
    what I find is that this query has duplicate value and null (',,') coming in as data has null and duplicate value. Is there a way i can avoid the null and the duplicate values in the query output?
    thanks,
    Edited by: orausern on Feb 19, 2010 5:05 AM

    Hi,
    Try this code.
    with
    t as ( select substr(value,2)value,ind
            from test1
            model
            ignore nav
            dimension by (id)
            measures (cast(value as varchar2(100)) value, 0 ind)
            rules
            ( ind[any]=  instr(value[cv()-1],value[cv()]),
            value[any] order by id = value[cv()-1] || CASE WHEN value[cv()] IS NOT NULL
                                               and ind[cv()]=0     THEN ',' || value[cv()] END      
    select max(value) oneline
    from t;
    SQL> select * from test1;
            ID VALUE
             1 Value1
             2 Value2
             3 Value3
             4 Value4
             5 Value4
             6
             7 value5
             8
    8 ligne(s) sélectionnée(s).
    SQL> with
      2   t as ( select substr(value,2)value,ind
      3          from test1
      4          model
      5          ignore nav
      6          dimension by (id)
      7          measures (cast(value as varchar2(100)) value, 0 ind)
      8          rules
      9          ( ind[any]=  instr(value[cv()-1],value[cv()]),
    10          value[any] order by id = value[cv()-1] || CASE WHEN value[cv()] IS NOT NULL
    11                                             and ind[cv()]=0     THEN ',' || value[cv()] END 
    12          )
    13        )
    14   select max(value) oneline
    15   from t;
    ONELINE
    Value1,Value2,Value3,Value4,value5
    SQL>

  • Using a variable in "arrayTerminatedBy" clause while using a file adapter

    Hi All,
    How can read a file of sample shown below using a file adapter.
    ABC|20081010|
    2008|xxxxxxx|
    2007|yyyy|
    2009|zzzzzzz|
    3|20081010|
    first line is the header
    last line is footer
    middle portion is the body
    '3' in the footer is the total no of record count in the body
    I am able to read the header and body.
    The problem i am facing is; when it is reading the footer it is treating the footer as a record in the body and is throwing an error stating - expected the format as "yyyy"
    I have to use "arrayTerminatedBy" to indicate the end of the body. But that terminating field is a varying field. How can i use this variable field in the "arrayTerminatedBy" clause.
    Can any one help in reading this file
    Thanks in advance
    Edited by: user10308218 on 11-Oct-2008 02:23
    Edited by: user10308218 on 11-Oct-2008 02:24

    See if this helps, I haven't tested it but it will give you a hint in how to achieve it. As you can see I use the startsWith command. I'm not sure how to handle your detail as it seems to start with different elements every time.
    cheers
    James
    <?xml version="1.0" encoding="UTF-8" ?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd"
    targetNamespace="http://TargetNamespace.com/Write_File"
    xmlns:tns="http://TargetNamespace.com/Read_File"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified" nxsd:encoding="ASCII" nxsd:stream="chars" nxsd:version="NXSD">
    <xsd:element name="FileRecord">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="Header" nxsd:startsWith="ABC|" maxOccurs="1">
    <xsd:complexType>
    <xsd:sequence nxsd:style="array" nxsd:arrayTerminatedBy="${eol}">
    <xsd:element name="FileDate" type="xsd:string" nxsd:style="terminated" nxsd:terminatedBy="${eol}" nxsd:quotedBy="&quot;"/>
    <xsd:element name="Record" maxOccurs="unbounded">
    <xsd:complexType>
    <xsd:sequence nxsd:style="array" nxsd:arrayTerminatedBy="${eol}">
    <xsd:element name="DetailData1" type="xsd:string" nxsd:style="terminated" nxsd:terminatedBy="|" nxsd:quotedBy="&quot;"/>
    <xsd:element name="DetailData2" type="xsd:string" nxsd:style="terminated" nxsd:terminatedBy="${eol}" nxsd:quotedBy="&quot;"/>
    <xsd:element name="Footer" nxsd:startsWith="3|" maxOccurs="unbounded">
    <xsd:complexType>
    <xsd:sequence nxsd:style="array" nxsd:arrayTerminatedBy="${eol}">
    <xsd:element name="FooterData" type="xsd:int" nxsd:style="terminated" nxsd:terminatedBy="${eol}" nxsd:quotedBy="&quot;"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>

Maybe you are looking for