Dataytpe mismatch error in GROUP BY Clause

I have a function(undergoing testing) which returns column values separated by comma. Since this function returns a huge number of values (track_id) which a varchar2 type can't store i've made the return type to be CLOB.
CREATE OR REPLACE FUNCTION get_shp_no_list
p_shp_nbr IN VARCHAR2
) RETURN clob
AS
  type shp_list_type is table of shp_trkg_dtl.track_ID%type;
  v_shp shp_list_type;
  v_ship_list  CLOB; 
BEGIN
     -- get all track_ids for the selected shp_nbr
     SELECT DISTINCT (track_id )
     BULK COLLECT INTO v_shp
     FROM shp_trkg_dtl
     WHERE shp_id = p_shp_nbr
     ORDER BY track_ID;
     FOR i IN v_shp.FIRST .. v_shp.LAST LOOP
         IF v_ship_list IS NULL THEN
            v_ship_list := v_shp(i);
         ELSE
            v_ship_list := v_ship_list || ',' || v_shp(i);
         END IF;
     END LOOP;     
     --return the track_id list
     RETURN v_ship_list;
EXCEPTION
  WHEN OTHERS THEN
    RETURN NULL;
END get_shp_no_list;
/This function works fine when called as standalone. But when i use this function in a SELECT in a stored proc i am getting error. My query looks like
SELECT .......
FROM
(SELECT sd.shp_id,get_shp_no_list(sd.shp_id) trackids,
FROM shp_trkg_dtl sd
WHERE sd.shp_id IN  ('LPNR0456T','LPNR0498Y','LPNG0471G','LPNG783H') source1
INNER JOIN ........................
Group By source1.trackids  -- -<font color="red"><b> line where error has occured</b></font>
ERROR at line 15:
ORA-00932: inconsistent datatypes: expected - got CLOBAny thoughts?

Taken from the 10.2 manual:
Restrictions on the GROUP BY Clause:
This clause is subject to the following restrictions:
You cannot specify LOB columns, nested tables, or varrays as part of expr.
The expressions can be of any form except scalar subquery expressions.
If the group_by_clause references any object type columns, then the query will not be parallelized.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#i2065646

Similar Messages

  • Error in group by clause

    Tables: contributions: emp_code, curr_month,contribution_amt
    10          200912        541
    10          201001        541
    10          201002        541mst_3ps: emp_code, eps_no, epf_estd_code
    mst_estd: epf_estd_code, epf_region_code, epf_subregion_code.ESTD_NAME,ESTD_ADDR1,ESTD.ESTD_ADDR2
    Input: select trunc((contributions.curr_month/100),0),  
            sum(contributions.contribution_amt),
            mst_3ps.eps_no,  
            mst_estd.epf_estd_code,  
            mst_estd.epf_region_code,  
            mst_estd.epf_subregion_code,  
            mst_estd.estd_name,  
            mst_estd.estd_addr1,  
            mst_estd.estd_addr2
        from mst_3ps,  
               mst_estd,
               contributions 
       where  ( contributions.emp_code = 10 ) and
             ( mst_3ps.epf_estd_code = mst_estd.epf_estd_code ) and 
            (mst_3ps.emp_code = 10423 )
            group by  TRUNC((contributions.CURR_MONTH/100),0)  Output/Error: ORA-00979: not a GROUP BY expression

    Hi,
    For a longer explanation of what Boneist said, see this thread:
    Re: Need help
    Depending on your data and your needs, an alternative to the solution Boneist suggssted is to do a GROUP BY sub-query involving only the contributions table, and then join that result set to the other tables.
    The query you posted does not have any join condition between contributions and either of the other tables. is that really what you want?
    If you'd like help, post a little sample data (CREATE TABLE and INSERT statements for all tables) and the results you want from that data.

  • GROUP BY Clause -SQL Devolper error 00904. 00000 -  "%s: invalid identifier

    I'm a real novice with SQL and I am having a problem understanding why this doesn't work. Searching the web got me to this forum, but I haven't been able to find a solution. Obviuosly I don't really understand how to use the GROUP BY clause. The SQL works fine without that clause.
    As stated in the subject I am getting this error:
    ORA-00904: "SORTPLAN": invalid identifier
    00904. 00000 - "%s: invalid identifier"
    *Cause:   
    *Action:
    Error at Line: 9 Column: 17
    With this SQL statement:
    SELECT START_DTM,
    END_DTM,
    MACHINE_SORT_PROGRAM_NAME as Sortplan,
    sum(TOTAL_PIECES_FED_CNT) AS TotalFed
    FROM END_OF_RUN
    WHERE MODS_DATE BETWEEN '27-Jul-2011' AND '27-Jul-2011'
    AND MAIL_OPERATION_NBR =919
    AND SITE_ID = 81003
    GROUP BY Sortplan
    ORDER BY Sortplan;
    TIA
    Mike

    Gary,
    Thank you for pointing me in the right direction. There are so many choices here I had a hard time deciding which to use. :)
    I tried your suggestion and still got an error. I had thought I didn't need to use aggregate functions on all of the fields. I guess that was wrong, so I changed it. Once I did that the SQL worked fine.
    ORA-00979: not a GROUP BY expression
    00979. 00000 - "not a GROUP BY expression"
    *Cause:   
    *Action:
    Error at Line: 2 Column: 3
    SELECT MACHINE_SORT_PROGRAM_NAME AS Sortplan,
    min(START_DTM),
    max(END_DTM),
    sum(TOTAL_PIECES_FED_CNT) AS TotalFed
    FROM END_OF_RUN
    WHERE MODS_DATE BETWEEN '27-Jul-2011' AND '27-Jul-2011'
    AND MAIL_OPERATION_NBR =919
    AND SITE_ID = 81003
    GROUP BY MACHINE_SORT_PROGRAM_NAME
    ORDER BY Sortplan;
    Mike

  • Why is the GROUP BY clause not working in my Query?

    Dear All,
    Below is the Query for a Summary Debtors Aged Analysis.
    The GROUP BY clause does not seem to be working.
    The Query returns all the unpaid invoices, instead of a single total row for each Customer.
    If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
    I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
    This is what GROUP BY is supposed to do, but it is not doing its work.
    What has gone wrong?
    Thanks
    Leon Lai
    Here's my Query:
    declare @taxdt datetime
    set @taxdt
    /*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
    SELECT
    CASE
                 WHEN T0.Account = 1220101 THEN 'Prim Cust'
                 WHEN T0.Account = 1220102 THEN 'Fgn Cust'
                 WHEN T0.Account = 1220103 THEN 'Local Cust'
                 WHEN T0.Account = 1220104 THEN 'Staff Loan' 
                 WHEN T0.Account = 1220105 THEN 'Dep with TP'
                 WHEN T0.Account = 1220106 THEN 'Adv to Cust'
                 WHEN T0.Account = 1220108 THEN 'Sund Drs'
                 ELSE 'Error ! ! !'
    END AS 'Control A/c',
    T1.CardCode AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',       
    SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',     
    ((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
        WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))    
        AS '1 Mth Ago' 
    /* Similarly for other age brackets*/
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C'
    and (Balance) != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDate

    Dear Neetu,
    Thanks for your reply.
    This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
    http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
    So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
    Once I understand the problem, I can adapt your query to suit my requirements
    So, let's start with a clean slate:
    The Query you have posted is for a DETAILED Debtors Aging Report.
    This lists all outstanding invoices, and ages them in the Age Brackets.
    What I want is a SUMMARY Debtors Aging Report.
    This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
    There will be a single row listed for each customer, something like this:
    Customer     Total Due     Current      1 Mth          2 Mth         3 Mth  etc
    Alfred       500,000       300,000       200,000
    Charles      800,000                     100,000       300,000       400,000
    How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
    Thanks
    Leon Lai
    Here's your code
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

  • -- SQL -- GROUP BY clause: non-aggregate fields mandate

    Hello,
    I was studying Databases, (particularly the retrieval of the data), and found something interesting.
    While using an Aggregate Function in the SELECT clause, it is mandatory to have all the non-aggregate fields in the SELECT clause to be there in the GROUP BY clause.
    For example,
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    The above SQL works fine.
    But, what if the user misses the dept_no in the GROUP BY clause or he/she misses the GROUP BY clause itself?
    Certainly, it is an error.
    Why is this error not handled by the database. I mean, the database should be smart/intelligent enough to add the GROUP BY clause by itself. So suppose, if I miss out the GROUP BY clause or miss a non-aggregate field from the SELECT clause when I am having at least one aggregate function on a field with at least one non-aggregated field in the SELECT clause, the database should check the GROUP BY clause at time of compilation and add the mandate missed out fields in the GROUP BY clause.
    Example,
    SQL1:_
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    SQL2:_
    SELECT dept_no, SUM(salary)
    FROM employee;
    Here, the SQL1 and SQL2, both should give me same outputs without an error.
    I am unable to understand why is this not handled?

    Hi,
    998478 wrote:
    ... If we mix aggregate and non-aggregate values then there must be a GROUP BY clause containing all the non-aggregate values. Why is this not handled by the database/compiler itself? It IS handled by the compiler itself. The compiler handles it by raising an error. The compiler has no way of knowing whether you want to remove something from the SELECT clause, or to add something to the GROUP BY clause, or not to use aggregate functions, or to use more aggregate functions, or some combination of the above. If the compiler re-wrote your code, and did any of these things automatically, it would be wrong more often than it was right, and you would (rightly) be complaining about its behavior.
    For example, this is clearly wrong:
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;What is the right way to fix it?
    <h3>1. Remove something from the SELECT clause</h3>
    SELECT    deptno
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;<h3>2. Add something to the GROUP BY clause</h3>
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ,         job
    ;<h3>3. Not use aggregate functions</h3>
    SELECT    deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ;<h3>4. Use more aggregate functions</h3>
    SELECT    deptno
    ,       MIN (job)
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;These aren't all the options, either. For example, the correct fix might be to use analytic functions instead of aggregate functions.
    How can anybody say which of these is right? All of them are the right answer for some problem.
    By the way, saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit over-simplified.
    More completely, here are the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate function, then everything in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can SELECT "TO_CHAR (TRUNC(dt), 'Mon-DD')").
    Edited by: Frank Kulash on Apr 13, 2013 1:44 PM
    Added code examples.

  • Right GROUP BY clause

    I wrote the view in the Original View section below. I query it with the following SELECT statement:
    SELECT *
    FROM ZZBUD_DEBT_SERVICE_V
    WHERE action_month IN ('01','02')
    AND action_year IN ('2011')
    AND short_name IN( 'WHIT-18','2REDFERN')
    ORDER BY action_year,action_month, group1, group2, short_name;
    An get these results:
    SHORT GROUP1 GROUP2 ACTION ACTION CURR CURR CURR
    NAME YEAR MONTH INT INT PRIN
    ACCRUED PAYMENT PAYMENT
    2REDFERN     05     02 2011 01     149.39     0     0     
    2REDFERN     05     02 2011 02     0     896.32 49795.84     
    WHIT-18     05     01 2011 01     442.86     0     0     
    WHIT-18     05     01 2011 02 442.86 2657.14 0     
    I need to compute the year-to-date CURR_INT_ACCRUED, CURR_INT_PAYMENT, CURR_PRIN_PAYMENT (SUM(CURR_INT_ACCRUED), etc.) by short_name and action_year but I can't tweek my GROUP BY statement properly. What would the GROUP BY expression look like to get the sum of these columns?
    Original View:
    CREATE OR REPLACE VIEW ZZBUD_DEBT_SERVICE_V(short_name, group1, group2, action_year, action_month
    , curr_int_acrrued, curr_int_payment, curr_prin_payment)
    AS
    SELECT short_name, group1, group2, action_year, action_month
    , SUM(curr_int_acrrued) curr_int_acrrued
    , SUM(curr_int_payment) curr_int_payment
    , SUM(curr_prin_payment) curr_prin_payment
    FROM (
    SELECT dsa.short_name
    , dsa.group1
    , dsa.group2
    , dsa.action_year
    , dsa.action_month
    , DECODE(SIGN(dsa.int_accrued),-1,0 ,0,0,dsa.int_accrued) curr_int_acrrued
    , DECODE(SIGN(dsa.ytd_accrued),1,0,0,0,ABS(dsa.ytd_accrued)) curr_int_payment
    , DECODE(SIGN(dsa.bond_outstand),1,0,0,0,ABS(dsa.bond_outstand)) curr_prin_payment
    FROM NYC.ZZBUD_DEBT_SERVICE_MASTER DSA
    WHERE dsa.bond_status = 'A'
    AND dsa.group1 IN ('03', '05', '06', '07')
    ORDER BY dsa.group1, dsa.group2, DSA.short_name, dsa.action_year, dsa.action_month
    GROUP BY short_name,group1,group2,action_year,action_month

    It depends on how you look at it. When I issue the command:
    SELECT group1, group2, short_name,SUM(curr_int_acrrued) ytd_accrued_int
    FROM ZZBUD_DEBT_SERVICE_V
    WHERE action_month IN ('01','02')
    AND action_year IN ('2011')
    AND short_name IN ('BXRIVER','WILSON','WHIT-18','2REDFERN')
    GROUP BY action_year,action_month,group1, group2, short_name
    ORDER BY action_year,action_month, group1, group2, short_name
    I'm not getting the results I want as 'WHIT-18' shows detail for both action_months and I want the SUM of 01 & 02 and the same for the other short_names. When I drop columns from the GROUP BY clause I get error ORA-0979 'Not a GROUP BY expression'.

  • Columns not to be included in group by clause

    I have a select query where i need to display count of records group by state_name
    In my main select query i need to include two more columns which are not be included in group by clause so that the number of records displayed does not increase
    I need to pass all these values from front end application so that i get count of records only by statename
    But when i include these two columns in my select query my query is throwing an error bcoz i have not included them in my group by
    How can we prevent this by not adding it to group by clause

    One general approach is (using the emp dept example)
    I want
    deptno dname, count(distinct empno)
    I can do that
    select d.deptno, d.dname, count(distinct e.empno)
    from dept d, emp e
    where e.deptno=d.deptno
    group by d.deptno, d.dname;
    or
    select d.deptno, d.dname, count_emp
    from dept d,
    (select e.deptno, count(distinct empno)
    from emp e
    group by e.deptno
    where d.deptno = e.deptno
    or depending on version (you don't mention versionk, though most questions have version dependent answers)
    select deptno
    , dname
    , (select count(distinct empno) from emp e where e.deptno=d.deptno)
    from dept d
    Obviously you can also use the FIRST and the LAST function to avoid having to include a column in the GROUP BY clause.
    Sybrand Bakker
    Senior Oracle DBA

  • How to ORDER BY Different column than in the group by clause.

    Hello, I have this sql statement
    SELECT COUNT([Tags]) AS CNT, [Tags]
    FROM [Tags], [Images]
    WHERE
    ([Images].[Tags] LIKE '%' + [Tags].[LongTag] + '%') AND
    ([Tags].AllowTagPost = 'True' )
    GROUP BY [Images].[Tags]
    HAVING COUNT([Tags]) > 30
    ORDER BY [Tags].[LastTagPost] DESC
    It returns the tags, the number of occurances sorted by count.  However, I want to sort it by a column in the Tags table named LastTagPost (DATETIME)  The idea is to get the tag that hasn't been used in the longest time and also has more occurances
    than 30 in the image table.  When I try to order by this column i get an error that i'm sure most of you are all to familer with.
    Error:
    Column "Tags.LastTagPost" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
    Any help would be greatly appreciated.

    Couldn't you just include the LastTagPost as a MIN?
    DECLARE @tags TABLE (LastTagPost DATETIME, LongTag VARCHAR(100), allowTagPost CHAR(5))
    DECLARE @images TABLE (tags VARCHAR(10))
    SELECT COUNT(i.Tags) AS CNT, i.Tags, MIN(t.LastTagPost) AS lastTagPost
    FROM @Tags t
    INNER JOIN @Images i
    ON i.Tags LIKE '%' + t.LongTag + '%'
    WHERE t.AllowTagPost = 'True'
    GROUP BY i.Tags
    HAVING COUNT(i.Tags) > 30
    ORDER BY LastTagPost DESC
    Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

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

  • ORA-00907: missing right parenthesis when using group by clause with xmlagg

    I have the following query and I am getting ORA 00907 Error when I am using group by clause with the xmlagg function.
    select xmlelement("Mitigation",
                    xmlelement("m_szMethodName",tm.DisplayName),
                    xmlelement("SubstanceInterferenceProtocolList",
                                (select xmlagg(xmlelement("MitigationProtocol",
                                        xmlelement("m_szMethodName",tm.DisplayName),
                                        xmlelement("m_szInterferenceProtocolName",tmp.protocol_name),
                                        xmlelement("m_szInterferenceSubstance",tmp.intf_mtrl_prod_code),
                                        xmlelement("m_ProtocolParameters",
                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                xmlelement("m_Consumables",
                                                    xmlelement("Consumable",
                                                        xmlelement("m_szConsumId", xrl.rgnt_pack_name),
                                                        xmlelement("m_szProductCode",xrl.pack_prod_code),
                                                        xmlelement("m_nVolume",tmp.fluid_vol),
                                                        xmlelement("m_szProtocolStep",xps.protocol_step_name))),
                                                    xmlelement("m_ProtParamList",
                                                        xmlagg(
                                                        xmlelement("ParameterValues",
                                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                            xmlelement("m_Time",xpsd.parameter_ntime_value))
                                                        group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)
                    order by tmp.ccd_test_id, tmp.intf_mtrl_prod_code, xps.protocol_step_intprotocolstep )
                    from XPR_tdef_mitigation_protocol tmp, xp_reagentlist xrl,
                    xpr_protocol_settings xps, xpr_protocol_settings_default xpsd
                    where tmp.ccd_test_id = tm.ccd_test_id
                    and tmp.ccd_test_id = xrl.ccd_test_id
                    and tmp.pack_prod_code = xrl.pack_prod_code
                    and tmp.intf_type = 1
                    and xps.protocol_name = xpsd.protocol_name
                    and xps.protocol_step_name = xpsd.protocol_step_name
                    and xps.ps_action_parameterlist = xpsd.ps_action_parameterlist
                    and xps.protocol_name =  tmp.PROTOCOL_NAME
    from XPtoXPRTdef_defn_mapping tm
    where tm.DisplayName = 'SYPH'If I remove the xmlagg clause along with the group by clause, the query runs fine and give me the output.
    But in that XML format of the output is incorrect for my application.
    Could someone help here?

    Hi,
    userAtoZ wrote:
    I have the following query and I am getting ORA 00907 Error when I am using group by clause with the xmlagg function.
    ... xmlagg(
    xmlelement("ParameterValues",
    xmlelement("m_szProtocolName",tmp.protocol_name),
    xmlelement("m_Time",xpsd.parameter_ntime_value))
    group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)Please don't post unformatted code. When posting 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 the code above were formatted well, so that you could match each '(' with its closing ')', it would look something like this:... xmlagg ( xmlelement ( "ParameterValues"
                        , xmlelement ( "m_szProtocolName"
                                       , tmp.protocol_name
                        , xmlelement ( "m_Time"
                                       , xpsd.parameter_ntime_value
    group by tmp.ccd_test_id
                        ,     tmp.intf_mtrl_prod_code
    This is exactly what you posted, only the whitespace has been changed.
    This makes it clear that the GROUP BY is inside the parentheses with the argument to XMLAGG.  You can have an ORDER BY clause there, but not a GROUP BY clause.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Strange behavior in inner query with group by clause

    Hi All,
    I found a very strange behaviour with Inner query having a group by clause.
    Please look the sample code
    Select b,c,qty from (select a,b,c,sum(d) qty from tab_xyz group by b,c);
    This query gives output by summing b,c wise. But when i run the inner query it gives error as "not a group by expression "
    My question is - though the inner query is wrong, how is it possible that this query gives output.
    it behaves like -
    Select b,c,qty from (select b,c,sum(d) qty from tab_xyz group by b,c);
    Is it a normal behaviour ?
    If it is a normal behaviour, then how group by behaves inside a inner query.
    Thanks !!

    This case I have tested already and it throws error.
    But why the initial posted query is not throwing
    error even the inner query is wrong.
    In what way oracle behaves for the initial posted
    query?what is the scenario that throws the error? is it at the time when you only run the inner query or the whole query?

  • Use of expressions or field aliases in GROUP BY clauses

    I've seen numerous references, even BNF syntax
    diagrams, that suggest that Oracle's parser will accept an expression in a
    GROUP BY clause; however, I've had no success whatsoever in getting this to
    work. Here's an example of something I had hoped would work, but does not:
    SELECT
    account_id,
    CASE
    WHEN txn_date BETWEEN DATE '2006-06-01' AND DATE '2006-06-07' THEN 1
    WHEN txn_date BETWEEN DATE '2006-06-08' AND DATE '2006-06-14' THEN 2
    ELSE 3
    END AS week_id,
    COUNT(*) AS week_cnt
    FROM myschema.my_random_table_name
    GROUP BY account_id, week_id;
    The interpreter gags on the use of "week_id" in the GROUP BY statement.
    Evidently Oracle syntax doesn't support the use of positional designations
    in aggregating statements either - I tried using the clause
    GROUP BY 1, 2;
    as the last line, and it didn't like this either.
    Any assistance or suggestions you can offer would be greatly appreciated.
    I prefer to let the DBMS engine do my aggregating for me as much as
    possible, but without being able to aggregate relative to programmer-defined
    fields, I am somewhat hamstrung.

    try this :
    SQL> select case when hire_date between '01-JAN-00' and '31-DEC-05' then 1 else 0 end col1, count(*)
    2 from employees
    3 group by col1;
    group by col1
    ERROR at line 3:
    ORA-00904: "COL1": invalid identifier
    SQL>
    SQL>
    SQL>
    1 select case when hire_date between '01-JAN-00' and '31-DEC-05' then 1 else 0 end col1, count(*)
    2 from employees
    3* group by case when hire_date between '01-JAN-00' and '31-DEC-05' then 1 else 0 end
    SQL> /
    COL1 COUNT(*)
    1 11
    0 96

  • Issue in group by clause.

    Hi,
      I am using a select query to retrieve sum of few numeric fields as below.
    select field1 field2
             sum ( field3 ) as field3
             sum ( field4 ) as field4
    into table t_tab1
    from dbtab
    where field1 in s_field1
    and   field2 in s_field2
    and   field <> 'RNIC'
    group by field1 field2.
    above code while syntax check gives error stating field 'RNIC' is missing in group by.
    When I remove group by, program gives a short dump.
    Please help me in resolving this issue.
    Thanks in advance.
    Suresh.

    Hi Rich,
       I am using equals opereator in the select query, if I remove the group by clause, no syntax errors appears but program gives dump saying the table mentioned in from clause does not have any field by 'SUM'. However if I mention group by clause it gives syntax error,
    please suggest....
    Suresh.
    this is my select query.
      SELECT rcomp racct robukrs
             sum ( tslvt ) AS tslvt
             sum ( tsl01 ) AS tsl01
             sum ( tsl02 ) AS tsl02
             sum ( tsl03 ) AS tsl03
             sum ( tsl04 ) AS tsl04
             sum ( tsl05 ) AS tsl05
             sum ( tsl06 ) AS tsl06
             sum ( tsl07 ) AS tsl07
             sum ( tsl08 ) AS tsl08
             sum ( tsl09 ) AS tsl09
             sum ( tsl10 ) AS tsl10
             sum ( tsl11 ) AS tsl11
             sum ( tsl12 ) AS tsl12
        FROM (w-tabnm)  CLIENT SPECIFIED
        INTO TABLE t_zzallt
         WHERE rclnt   EQ syst-mandt
         AND rcomp     IN s_rcomp
         AND racct     IN s_saknr
         AND racct     IN aoacct_range
         AND ( rcomp  NOT IN aononk4rcomp_range )
         AND ryear     EQ p_year
         AND  ( ( rldnr = 'PS' AND rcomp  NOT IN aopsrcompx_range ) OR
                ( rldnr  NOT IN ao_ledgerx_range ) )
       GROUP BY rcomp racct robukrs.

  • CFQUERYPARAM tag not working in GROUP BY clause

    I am getting an error whenever I put a CFQUERYPARAM tag in a
    GROUP BY clause. I saw on another message board someone was having
    a similar problem with the ORDER BY clause
    Here is a sample of what my code might look like
    select x, y, z from abc
    group by <cfqueryparam value="x"
    cfsqltype="cf_sql_float">
    Here is the error I receive.
    Error Executing Database Query.
    [Macromedia][Oracle JDBC Driver][Oracle]ORA-00979: not a
    GROUP BY expression
    Any insight?

    The cachedwithin and cachedafter functions store the query
    results in the server's RAM. That means, while it's cached,
    whenever you run it, you get the cached result instead of going to
    the database to run it again. This increases speed of course, but
    if the data changes during the cache period, you have accuracy
    problems.
    It does not create memory issues. In the administrator you
    reserve a certain amount of memory for query caching. If you exceed
    that amount, the last query in pushes the first query out, or
    something like that.
    With regards to what you are trying to do about binding
    variables in your group by clause, that's not what cfqueryparam was
    designed for. It was designed for
    where clauses (where this = <cfqueryparam etc>
    or insert queries (insert into my table (field) values
    (<cfqueryparam>
    and things like that.
    You are trying to use it for something other than what it was
    designed for, which explains why it's not working for you.

  • Problem trying to use a group by clause

    hey good day,
    i'm trying to use a group by clause in my application, but I'm getting the following error.
    Error:-  Query cannot be parsed, please check the syntax of your query. (ORA-00979: not a GROUP BY expression)
    select      "INSTRUCTOR"."EMPNUM",
          "INSTRUCTOR"."FIRSTNAME",
          "INSTRUCTOR"."LASTNAME",
          "QUALN"."SPECIALIZE_FIELD" as "SPECIALIZE_FIELD",
             "INSTRUCTOR"."USERNAME"
    from      "QUALN" "QUALN",
          "INSTRUCTOR" "INSTRUCTOR"
    where   "INSTRUCTOR"."EMPNUM"="QUALN"."EMPNUM"
    group by "INSTRUCTOR"."EMPNUM", "INSTRUCTOR"."FIRSTNAME", "INSTRUCTOR"."LASTNAME"Thanks in advance,
    Richie

    Richie wrote:
    hey thanks for your reply,
    i have tried what you have suggested, but now i got another error
    Error :- The report query needs a unique key to identify each row. The supplied key cannot be used for this query. Please edit the report attributes to define a unique key column. ORA-01446: cannot select ROWID from, or sample, a ...
    This error message is not from oracle, btu from your reporting tool. it might be MS Access or whatever other tool that you use. Some of these tools want a unique value to identify the current row. The logic applied depends on the relationship of your tables. however in your case you could do it without the group by condition. THen the rowid can still be applied to your query.
    Example
    note the usage of alias names to simplified the select
    select      i.EMPNUM ,
          i.FIRSTNAME ,
          i.LASTNAME ,
             i.USERNAME
    from      INSTRUCTOR i
    where   i.EMPNUM in (select q.EMPNUM from QUALN q);

Maybe you are looking for