Grouping functions in SQL

Hello
My sql query returns this data below:
Column 1_ Column 2_ Column 3
A B C
A B D
I want it this way :
Column 1_ Column 2_ Column 3
A B C,D
How do I group this two rows column data which is common and separate the uncommon ones with comma delimited values and show the result...???

user9021545 wrote:
THE FORMATTING GETS MISALINGED BECAUSE OF PLAIN TEXT. TABLE A,TABLE B, TABLE C SHOULD BE UNDER COLUMN 3 UNDER MY DESIRED RESULT
Well as a member of 2 years and 186 posts, you should know how to format things on the forum by now.
Read {message:id=9360002} and this details how to use {noformat}{noformat} tags.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • PL/SQL equivalent of T-SQL - "group function is not allowed here"

    Hi all, hope someone can give me a hand as I'm pretty stuck! I have been trying to convert some MS SQL Server T-SQL statements into Oracle PL/SQL and am stuck on the below one:
    SELECT
    CA.AssessmentID,
    (SELECT ProductName + ISNULL(' - ' + PrincipalBenefit,'')
    FROM rptPolicySnapshot WHERE PolicyID = MAX(CA.PolicyID)
    AND SnapshotID = 1),
    MAX(CA.PolicyID)
    FROM rptClaimInvoiceLineSnapshot CIL
    INNER JOIN rptClaimAssessmentSnapshot CA
    ON CIL.AssessmentID = CA.AssessmentID
    AND CIL.SnapshotID = CA.SnapshotID
    WHERE CIL.SnapshotID = 1
    GROUP BY CA.AssessmentID
    This works fine in MSSQL but returns the below error in Oracle:
    'ORA-00934: group function is not allowed here'
    If I take out the subquery the query works fine.
    Any ideas as to the syntax? I am new to Oracle so not sure as to how I should go about writing this.
    Thanks in advance!
    Leo

    WITH x AS (SELECT   ca.assessmentid,
                        MAX (ca.policyid) policy_id
               FROM rptclaiminvoicelinesnapshot cil
                    INNER JOIN rptclaimassessmentsnapshot ca
                        ON cil.assessmentid = ca.assessmentid
                       AND cil.snapshotid = ca.snapshotid
               WHERE cil.snapshotid = 1
               GROUP BY ca.assessmentid
    SELECT x.assessment_id,
           x.policy_id,
           productname + decode(principalbenefit,null,null,' - ' || principalbenefit ) prodname
    FROM   rptpolicysnapshot, x
    WHERE  policyid = x.policy_id
    AND    snapshotid = 1I think that's in the neighbourhood.

  • PL/SQL: ORA-00934: group function is not allowed here

    Hi,
    I am writing a PL/SQL procedure. The structure is like :
    SET SERVEROUTPUT ON;
    CREATE OR REPLACE Procedure abc
    IS
    v_total_ip_rec number(14);
    v_total_op_rec number(14);
    v_total_rec number(14);
    BEGIN
    SELECT SUM (CASE
    WHEN <condition 1>
    THEN 1
    ELSE 0
    END
    ) into v_total_ip_rec,
    SUM (CASE
    WHEN <condition 2>
    THEN 1
    ELSE 0
    END
    ) into v_total_op_rec,
    SUM (1) into v_total_rec
    FROM A,B
    WHERE A.Col1=B.Col1;
    EXCEPTION
    WHEN OTHERS THEN
    raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
    END;
    When I run this procedure it gives me following error:
    "PL/SQL: ORA-00934: group function is not allowed here"
    Anybody have any idea?
    Any help would be appreciated.
    Thanks.

    Hi Arunkumar ,
    I think you don't need subquery.
    Regards Salim.
    Or.
    SELECT COUNT (CASE
                     WHEN <condition 1>
                        THEN 1
                  END) v_total_ip_rec,
           COUNT (CASE
                     WHEN <condition 2>
                        THEN 1
                  END) v_total_op_rec,
           COUNT (1) v_total_rec
      FROM a, b
    WHERE a.col1 = b.col1

  • GROUP DATA PL/SQL FUNCTIONS CALLABLE FROM SQL

    MAKE GROUP DATA PL/SQL FUNCTIONS (IE. TABLE TYPE PARAM) CALLABLE FROM SQL
    Is it possible to create new group function like AVG or to overload them ?
    null

    Application Developer's Guide (A76939, page 9-60) list a few requirements from user-defined SQL function, and one of them is:
    * It must be a row function, not a column (group) function; in other words, it
    cannot take an entire column of data as its argument.
    But if anyone find a way to do it, please let me know.

  • Grouping Function usage in SQL

    All,
    How does grouping function work, does it also depends on the sequence of columns used in group by rollup
      select deptno,job, group_id(), sum(sal), grouping(deptno) , grouping(job)
      from emp
      group by rollup (deptno, job) 
      If the query is run by "rollup(job,deptno)" grouping (deptno) returns 1 where as if "rollup(deptno,job)" grouping (deptno) returns 0.
    Does the column sequence in group by rollup decides the returning of grouping(deptno) function. I feel to have some misunderstanding of the way its said in ORACLE documentation. We referred to the below link for our understanding.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions071.htm
    Request the PRO's to discuss and clarify on this.

    Hi,
    ramarun wrote:
    All,
    How does grouping function work, GROUPING (x) returns 1 if the current row represents a superaggregate of x, and 0 otherwise. In other words, if GROUPING (x) is 0, then the row represents a single value of x. If GROUPING (x) is 1, then the row represents a total of all values of x.
    For example the query you posted may produce results like this:
    `   DEPTNO JOB       GROUP_ID()   SUM(SAL) GROUPING(DEPTNO) GROUPING(JOB)
            20 ANALYST            0       6000                0             0
               ANALYST            0       6000                1             0
            10 CLERK              0       1300                0             0
            20 CLERK              0       1900                0             0
            30 CLERK              0        950                0             0
               CLERK              0       4150                1             0
            10 MANAGER            0       2450                0             0
            20 MANAGER            0       2975                0             0
            30 MANAGER            0       2850                0             0
               MANAGER            0       8275                1             0
            10 PRESIDENT          0       5000                0             0
               PRESIDENT          0       5000                1             0
            30 SALESMAN           0       5600                0             0
               SALESMAN           0       5600                1             0
                                  0      29025                1             1Look at the last three rows. On this row
    `   DEPTNO JOB       GROUP_ID()   SUM(SAL) GROUPING(DEPTNO) GROUPING(JOB)
            30 SALESMAN           0       5600                0             0GROUPING (deptno) is 0; so the row represents only deptno=30.
    GROUPINT (job) is 0, so the row represents only job='SALESMAN'.
    SUM (sal) is 5600, so the total salary of all salesmen in department 30 is 5600.
    Now look at this row:
    `   DEPTNO JOB       GROUP_ID()   SUM(SAL) GROUPING(DEPTNO) GROUPING(JOB)
               SALESMAN           0       5600                1             0GROUPING (deptno) is 1; so the row does not represent any one deptno; it is a superaggregate of all deptnos. Notice that the deptno column is NULL, even though there are no rows in the table where deptno is NULL.
    GROUPING (job) is 0, so the row represents only job='SALESMAN'.
    SUM (sal) is 5600, so the total salary of all salesmen in any department is 5600. (As it happens, all the salesmen are in department 30, so this sum is the same as on the previous row.)
    Now look at the last row:
    `   DEPTNO JOB       GROUP_ID()   SUM(SAL) GROUPING(DEPTNO) GROUPING(JOB)
                                  0      29025                1             1GROUPING (deptno) is 1; so the row does not represent any one deptno; it is a superaggregate of all deptnos. Notic that both deptno and job are both NULL on this row of output, even though neither column is ever NULL in the table.
    GROUPING (job) is 0, so the row represents only job='SALESMAN'.
    SUM (sal) is 5600, so the total salary of people with any job and any department is 29025.
    does it also depends on the sequence of columns used in group by rollup Excellent question! Try it an see. Change the order or columns in the GROUP BY clause and see. If you get different results, then the order does matter.
    select deptno,job, group_id(), sum(sal), grouping(deptno) , grouping(job)
    from emp
    group by rollup (deptno, job)  If the query is run by "rollup(job,deptno)" grouping (deptno) returns 1 where as if "rollup(deptno,job)" grouping (deptno) returns 0. You get different results; therefore the order does matter.
    Does the column sequence in group by rollup decides the returning of grouping(deptno) function...Yes.
    "GROUP BY ROLLUP (deptno, job)" means a superaggregate row for each value of job, representing all deptnos, will be formed. That is, you will get one row representing all analysts; another row representing all clerks, another row representing all managers, and so on. This will be similar to the results that you would get if you never mentioned the first expression in the ROLLUP list, that is, deptno. You will not get a superaggregate row representing any one deptno, say, 10.
    "GROUP BY ROLLUP (job, deptno)" means a superaggregate row for each value of deptno, representing all jobs, will be formed. That is, you will get one row representing all anlysts; another row representing deprtment 10, another row representing department 20, and so on. This will be similar to the results that you would get if you never mentioned the first expression in the ROLLUP list, that is, job. You will not get a superaggregate row representing any one job, say, 'ANALYST'.

  • ORA-00935:  group function is nested too deeply - SQL Query is correct...

    select s.sname, to_char(sum(t.amount), 'fm$999999.00')
    from transactions t, salespeople s
    where t.sid = s.sid
    group by s.sname, t.year
    having (t.year = 1997) and max(sum(t.amount));
    I'm trying to print sales person name who had the highest total sell in 1997. I do not see where did i go wrong in the above query...Isn't nested group function allowed?!
    What about this?
    select s.sname, to_char(sum(t.amount), 'fm$999999.00') as "TOTAL"
    from transactions t, salespeople s
    where t.sid = s.sid
    group by s.sname, t.year
    having (t.year = 1997) and sum(t.amount) = (select max(amount) from transactions where year = 1997);
    It should return something, but it does not due lack of data in database. I think the above code is correct. I just need to confirm from you...

    select s.sname, (case when sum(t.amount) > sum(t2.amount)
    then sum(t.amount)
    else sum(t2.amount)
    end) "TOTAL"
    from transactions t, salespeople s
    where t.sid = s.sid
    group by s.sname, t.year
    having t.year = 1997
    union
    select s.sname, sum(t2.amount)
    from transactions t2, salespeople s
    where t2.sid = s.sid
    group by s.sname, t2.year
    having t2.year = 1997;
    Your code looks good, but it does not work in Oracle Developer...
    The above should work isn't it? The inner query gets executed then the outer one so the result i get in

  • Sql group function

    I am trying to calculate the average cost of the books for each customer. The output should contain the customer#, name and the average order.
    This is the code I have:
    SELECT AVG(SUM((retail-cost)*quantity))
    FROM orders JOIN orderitems USING (order#)
    JOIN books USING (isbn)
    JOIN customers USING (customer#)
    GROUP BY order#, customer#;
    I get either, over 8000 for the average order or about 33 for the average order when I don't include the name, customer number or anything else in the code. If I add any other information, I get:
    SELECT customer#, AVG(SUM((retail-cost)*quantity))
    ERROR at line 1:
    ORA-00937: not a single-group group function
    I'm sure there is something small that I am missing, but cannot see it.

    Hi,
    Whenever you have a question, you should post a little sample data and the results you want to get from that data.
    I don't know where you're coming from, or where you want ot go, so it's hard to give you good directions. All I have is your current route plan, which must be incorrect, or else you wouldn't be asking anything.
    I see you are nesting aggregate functions. That's very rare in real life, and the result is always to produce one row of output, regardless of what's in the GROUP BY clause.
    I suspect you want to do a SUM in a sub-query, and then do AVG on the results in the main query. Without seeing your sample data and desired results, I'm just guessing.

  • Want to convert function in SQL Server 2000

    Hi ,
    i am writing this function in oracle.Could you please convert this function in SQL Server 2000 because i am new in this and dont know how to use decode function in sql.
    Please following is the code for oracle.
    CREATE OR REPLACE function fun ( localex varchar2,titlex varchar2)
    return number
    as  x number;
    begin
    select sum ( decode (count (username),max(prereq_count),1,0) ) x into x from
       SELECT
                       prereq_count,
                       username
                 FROM
                         table1
    group by     username ;
    return x;
    end fun;
    Regards
    Vishal

    Just take a look example below might give you idea :
    create or replace function f_makeAddress_tx (
    i_address_tx VARCHAR2,
    i_city_tx VARCHAR2,
    i_state_tx VARCHAR2,
    i_zip_tx VARCHAR2)
    return VARCHAR2
    is
    e_badZip EXCEPTION; u279E8
    pragma EXCEPTION_init(e_badZip,-20998); u279E9
    v_out_tx VARCHAR2(256);
    begin
    p_validateZip (i_zip_tx); u279E12
    v_out_tx:= i_address_tx||u2019, u2018|| u279E13
    i_city_tx ||u2019, u2018||
    i_state_tx ||u2019, u2018||
    i_zip_tx;
    return v_out_tx; u279E17
    exception
    when e_badZip then u279E19
    return i_zip_tx || u2018: Invalid zip code.u2019;
    end;
    Regards,
    Clint

  • APEX, BI Publisher and SQL Query (PL/SQL Function returning SQL Query)..

    I don't know if I should be posting this in this Forum or the BI Publisher forum, so I am posting in BOTH forums..
    I love APEX, let me say that first.. And appreciate the support offered here by the group, but am running int a confusing issue when BI Publisher tries to build a report from the above type APEX report..
    Here is my dilemma:
    I have a number of reports that are part of a Oracle package. They return an SQL Query back to a reports region on a page. I am having to deal with the column names returned are col01, col02..
    The issue I have is, when building the Application Level query to download the XML sample from in building RTF layouts in Word, you can not use this code, you MUST use a standard SQL Select.
    I have taken the sql from the function returning sql, and copied into the application query, supplying the required data values for bind variables being used in the query.
    An XML file is produced, and I use this to build the RTF format file that I load back into APEX and try to use it for the PDF rendering of the report. I can view the output as a PDF in the Word add on, but when I try using it with the report, it is returning an empty PDF file.
    Can anyone tell me what error log files on the bi publisher side I can look at to see what error is happening?
    Thank you,
    Tony Miller
    UTMB/EHN
    Title changed, maybe SOMEONE has an idea on this??
    Message was edited by:
    Tony Miller

    Hi,
    1/ first check you are passing the bind variables and
    appropriate values in the call to your report - if
    the query returns no data then you get an empty page
    So if your query takes :P10_USERNAME variable then
    pass it to the report in the URL
    f?p=&APP_ID.:0:&SESSION.:PRINT_REPORT=YOUR_REP_QUERY_N
    AME:::P10_USERNAME:MYUSER
    2/ try to use the Default layout first to check your
    report query really returns the data when called
    3/ if you defined a header in your rtf template check
    there is no & (ampersand) - if using & in the header
    and preview the template from word it displays data
    OK, but if you use this template in the report query
    it fails to render the data (bug in Apex-> Bi
    Publisher integration maybe?)
    4/ If using the table in the rtf template check its
    width does not overflow the page margins - there is a
    problem with pdf export
    5/ check
    /oc4j/j2ee/home/application-deployments/xmlpserver/app
    lication.log forthe information on BI Publisher runs
    RadoIssue was in the APEX page having issues.. I recoded a new page and am able to generate BI Publisher based PDF files..
    Thank you,
    Tony Miller
    UTMB/EHN

  • How to create a dynamic multi-line function in SQL Server

    I am attempting to create a Multi-Line Function in SQL Server that accepts a dynamic WHERE clause as a parameter. I need this so that the function can be as versatile as possible for the filter that needs to be applied. I am unfortunately getting an error
    upon creation of the function.  I don't know how to solve the problem. Can someone advise me?
    SQL:
    SET
    ANSI_NULLSON
    GO
    SET
    QUOTED_IDENTIFIERON
    GO
    -- =============================================
    -- Author:
    -- Create date: 2/3/2014
    -- Description: This multiline function will accept a generic WHERE Clause and apply it to the query for return.
    -- =============================================
    CREATE
    FUNCTIONTESTMULTILINEFUNCTION
    @WHEREvarchar(1024)
    ,@CHANGEDDATEasdatetime
    RETURNS
    @TESTTABLE
    TABLE
    IDint
    ,REVint
    AS
    BEGIN
    Declare@SQLSTRINGvarchar(4096)
    SET@SQLSTRING=''
    SET@SQLSTRING=@SQLSTRING+'SELECT
    REVS.ID, REVS.Revision
    FROM
    Select distinct result.ID, Max(Rev) as ''''Revision''''
    FROM
    Select * from dbo.BugsAll
    where
    [Changed Date] < @CHANGEDDATE
    ) result
    GROUP BY result.ID
    ) REVS
    join dbo.BugsAll BA on (BA.ID=REVS.ID AND BA.REV=REVS.revision)'
    IF
    (@WHEREisnotnullOR@WHERE<>'')
    BEGIN
    SET@SQLSTRING=@SQLSTRING+'
    WHERE '+@WHERE;
    END
    INSERT@TESTTABLE
    EXEC
    (@SQLSTRING)
    RETURN
    END
    GO
    ERROR:
    Msg 443, Level 16, State 14, Procedure TESTMULTILINEFUNCTION, Line 44
    Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
    Senior Test Lead -- Microsoft

    >> Unfortunately I really need to form a dynamic query in a table valued function on the SQL SERVER. I have another tabled valued function that needs something returned as a table in order to further join the data. I am not allowed to use Stored
    Procedures in that function. <<
    You do know that real SQL programmers hate the proprietary nightmare of tabled valued functions?  This is how you procedural programmers avoid learning set-oriented declarative and functional programming. 
    Your mindset wants to write to a scratch tape or disk file (aka “tabled valued function result table”) just like you did BASIC, FORTRAN or COBOL. QL programmers do not have to materialize their data. We can use VIEW or a drive table as well as a base table. 
    >> Plus, there are occasions where I don't want to pass in a field [sic: columns are not fields] parameter or need to change a parameter list such that I don't wish the table function to filter by a particular field [sic] or other setting. <<
    What you want is a magical “Automobiles, Squids and Lady Gaga” function. An SQL programmer might write a complex VIEW then do simpler SELECTs off it. 
    >> My application pushes the WHERE clause from EXCEL to SQL to do the hard work as EXCEL is not the application in which I want to process the SQL statement and pass it via ODBC. I cannot run macros in Excel on the web.<< 
    This is a crazy language system. Usually we fetch data in SQL and then pass it to a math package, report writer, etc. We never keep logic (aka WHERE clauses) outside the database. 
    >> I am bummed about the fact that this feature doesn't work. It will up my server management costs to maintain unique tabular based functions based on WHERE clause query <<
    So stop writing those “tabular based functions”, change your mindset and start learning SQL and do it right. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to create a user_defined grouping function?

    I need to create a user_defined function and use it in my sql statement.
    I know the user_defined function can be used anywhere the build-in function can be used.In oracle,there are grouping functions.
    How can I create a user_defined grouping function and I can use it in my sql statement.

    Hi, can you explain exactly what you are trying to achieve:
    SQL> create or replace function my_func return number as
      2  begin
      3    return 5;
      4  end;
      5  /
    Function created.
    SQL> select deptno,my_func(),max(sal)
      2  from emp
      3  group by deptno,my_func()
      4  /
        DEPTNO  MY_FUNC()   MAX(SAL)
            10          5       5000
            20          5       3000
            30          5       2850

  • Not a single-group group function very urgent

    HI,
    select sum(avg(wait_to))+sum(avg(idle))+sum(avg(users))+sum(avg(system)) from system_cpu
    where hostid='DSCP02469' group by cpuid
    this query is working
    but i want cpuid group to be displayed
    so i wrote query like this.
    select cpuid,sum(avg(wait_to))+sum(avg(idle))+sum(avg(users))+sum(avg(system)) from system_cpu
    where hOstid=' ' group by cpuid it is throwing a error
    not a single-group group function.
    how can get sum of avg of colums,column based on some coloum
    group by column
    id,sum(avg( )) i have to get
    please give me solution.
    send me mail to [email protected]

    hi,
    thanku for immediate reply but
    if i do that
    select cpuid, a+b+c+d total_value from (select cpuid,
    sum(avg(wait_to)) a, sum(avg(idle)) b,sum(avg(users)) c,sum(avg(system)) d
    from system_cpu where hostid='DSCP02469' group by cpuid)
    SQL> /
    select cpuid, a+b+c+d total_value from (select cpuid,
    ERROR at line 1:
    ORA-00937: not a single-group group functionelse
    select cpuid, a+b+c+d total_value from (select
    sum(avg(wait_to)) a, sum(avg(idle)) b,sum(avg(users)) c,sum(avg(system)) d
    from system_cpu where hostid='DSCP02469' group by cpuid)
    SQL> /
    select cpuid, a+b+c+d total_value from (select
    ERROR at line 1:
    ORA-00904: "CPUID": invalid identifier2)
    can we use select in select case
    can we use select sal, case when sal then select * from emp like this
    with regards
    shannu sarma

  • Average Function in SQL

    Hi SQL Fans,
    I'm strugggling with the Averge function in SQL and not sure how this works. I want to show the Average Discount a Sales Person has given away in a set date period based on ORDR and RDR1
    SELECT T0.[SlpName], T2.[DiscPrcnt] as AVERAGE
    FROM OSLP T0  INNER JOIN ORDR T1 ON T0.SlpCode = T1.SlpCode INNER JOIN RDR1 T2 ON T1.DocEntry = T2.DocEntry
    WHERE T1.[DocDate] BETWEEN [%0] AND [%1]
    Suggestions will be appreciated

    Hi,
    Try this:
    SELECT T0.[SlpName], avg(T2.[DiscPrcnt]) as AVERAGE
    FROM OSLP T0  INNER JOIN ORDR T1 ON T0.SlpCode = T1.SlpCode INNER JOIN RDR1 T2 ON T1.DocEntry = T2.DocEntry
    WHERE T1.[DocDate] BETWEEN [%0] AND [%1] group by T0.[SlpName]
    Thanks & Regards,
    Nagarajan

  • Equivalent of ValueList function in SQL

    Hi,
    Is there an equivalent of valueList function in SQL? Here's
    what I am trying to do:
    Suppose I have the following table:
    Name -- Color
    John -- Green
    John -- Red
    Mike -- White
    I want to do a query such that the colors are aggregated as a
    list. So the result would be:
    Name -- Color List
    John -- Green, Red
    Mike -- White
    The only way I could think of doing this is to loop through
    each name in the table and doing ValueList in each loop. Is there a
    better way?
    Thanks.
    Min

    > I want to do a query such that the colors are aggregated
    as a list.
    If it _must_ be done in sql, there are some database options.
    Such as the one mentioned above. There are also some interesting
    approaches using xml path and cross apply with MS SQL 2005. I do
    not know about other databases.
    http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-sing le-row.html
    Bear in mind there are some performance implications with all
    of the methods. For example, a udf would execute once for each
    name. So the more records, the greater the impact.
    Another possibility is to use cfoutput's group attribute to
    create a list for each name. Assuming that is feasible ..

  • Nested group function without group xmlagg

    I am getting nested group function without group by xmlagg when using the xmlagg function inside another xmlagg function. Find the table structure and sample data here,
    CREATE TABLE "TEST_TABLE"
       ("KEY" NUMBER(20,0),
        "NAME" VARCHAR2(50 ),
        "DESCRIPTION" VARCHAR2(100 )
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (1,'sam','desc1');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (2,'max','desc2');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (3,'peter',null);
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (4,'andrew',null);
    select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions", 
               xmlagg(
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;Then i removed the xmlagg function from the above select query and used xmlelement instead
      select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions",            
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;This is working fine, but xml created with empty elements for Descriptions element for key 3 and 4 which has null values. I need don't need Descriptions element in the xml when it has null value. Please help me to resolve this.

    You can do it with a correlated subquery :
    SQL> select xmlserialize(document
      2           xmlelement("root",
      3             xmlagg(
      4               xmlelement("emp"
      5               , xmlforest(
      6                   t.key as "ID"
      7                 , t.name as "ename"
      8                 , (
      9                     select xmlagg(
    10                              xmlelement("Desc", d.description)
    11                              order by d.description -- if necessary
    12                            )
    13                     from test_desc d
    14                     where d.key = t.key
    15                   ) as "Descriptions"
    16                 )
    17               )
    18             )
    19           ) as clob indent
    20         )
    21  from test_table t;
    XMLSERIALIZE(DOCUMENTXMLELEMEN
    <root>
      <emp>
        <ID>1</ID>
        <ename>sam</ename>
        <Descriptions>
          <Desc>desc1_1</Desc>
          <Desc>desc1_2</Desc>
          <Desc>desc1_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>2</ID>
        <ename>max</ename>
        <Descriptions>
          <Desc>desc2_1</Desc>
          <Desc>desc2_2</Desc>
          <Desc>desc2_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>3</ID>
        <ename>peter</ename>
      </emp>
      <emp>
        <ID>4</ID>
        <ename>andrew</ename>
      </emp>
    </root>
    Or an OUTER JOIN + GROUP-BY :
    select xmlserialize(document
             xmlelement("root",
               xmlagg(
                 xmlelement("emp"          
                 , xmlforest(
                     t.key as "ID"
                   , t.name as "ename"
                   , xmlagg(
                       xmlforest(d.description as "Desc")
                       order by d.description -- if necessary
                     ) as "Descriptions"
             ) as clob indent
    from test_table t
         left outer join test_desc d on d.key = t.key
    group by t.key
           , t.name
    ;Edited by: odie_63 on 11 juil. 2012 14:54 - added 2nd option

Maybe you are looking for