SQL multiple SELECT query with xmlagg function- Data not pulled in the required fashion

Raghu picture Raghu · Jun 19, 2012 · Viewed 74.7k times · Source

My data in Oracle is something like this

NAME | DEP_VALUE | ID_DEP

Amy     1         AA1234
Bob     2         BB4321
Clara   1         CC5678
Clara   2         CC7890
John    1         JJ6543
John    2         JJ7865
John    3         JJ7654
Tom     1         TT0987
Tom     2         TT6541
Tom     3         TT4087
Tom     4         TT3409

I need the data to be pulled in this fashion

NAME  | DEP_VALUE |  ID_DEP

Amy     1         AA1234
Bob     2         BB4321
Clara   1;2       CC5678;CC7890
John    1;2;3     JJ6543;JJ7865;JJ7654
Tom     1;2;3;4   TT0987;TT6541;TT4087;TT3409

My query is as follows

SELECT name,
   Rtrim(Xmlagg (Xmlelement (e, dep_value
                                || ';')).extract  ( '//text()' ), ','),
   Rtrim(Xmlagg (Xmlelement (e, id_dep
                                || ';')).extract  ( '//text()' ), ',')
FROM   (SELECT emp_name,
           dep.dep_value,
           dep.id_dep
    FROM   emp
           inner join dep
                   ON emp.name = dep.name
    WHERE  id_name IN (SELECT name
                       FROM   altname
                       WHERE  id_emp IN (SELECT id_emp
                                         FROM   cnames
                                         WHERE  emp_lvl LIKE '%GGG%')))
    GROUP  BY name,
      dep_value  

The result that is displayed is

NAME  | DEP_VALUE |  ID_DEP

Amy     1;         AA1234;
Bob     2;         BB4321;
Clara   1;         CC5678;
Clara   2;         CC7890;
John    1;         JJ6543;
John    2;         JJ7865;
John    3;         JJ7654;
Tom     1;         TT0987;
Tom     2;         TT6541;
Tom     3;         TT4087;
Tom     4;         TT3409;

How can I pull the data as in the 2nd table? What is the error in my sql query?

Answer

Justin Cave picture Justin Cave · Jun 19, 2012

It sounds like you want to GROUP BY name rather than GROUP BY name, dep_value

SELECT name,
   Rtrim(Xmlagg (Xmlelement (e, dep_value
                                || ';')).extract  ( '//text()' ), ';'),
   Rtrim(Xmlagg (Xmlelement (e, id_dep
                                || ';')).extract  ( '//text()' ), ';')
FROM   (SELECT emp_name,
           dep.dep_value,
           dep.id_dep
    FROM   emp
           inner join dep
                   ON emp.name = dep.name
    WHERE  id_name IN (SELECT name
                       FROM   altname
                       WHERE  id_emp IN (SELECT id_emp
                                         FROM   cnames
                                         WHERE  emp_lvl LIKE '%GGG%')))
    GROUP  BY name