问题
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?
回答1:
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
回答2:
Just to provide further explanation on xmlagg, and add another option with Oracle 11g.
http://www.dba-oracle.com/t_display_multiple_column_values_same_rows.htm
select
deptno,
listagg (ename, ',')
WITHIN GROUP
(ORDER BY ename) enames
FROM
emp
GROUP BY
deptno
/
Output:
DEPTNO ENAMES
---------- --------------------------------------------------
10 CLARK,KING,MILLER
20 ADAMS,FORD,JONES,SCOTT,SMITH
30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD
回答3:
Try like this more simple
select NAME,replace(wm_concat(DEP_VALUE),',',';') as DEP_VALUE, replace(wm_concat(ID_DEP),',',';') as ID_DEP from yourtable
where dep_value<2000 group by NAME
note: you need to limit your dep_value length and you can make your assumption, because you cannot get your string result to long, hope this is help your job
来源:https://stackoverflow.com/questions/11104896/sql-multiple-select-query-with-xmlagg-function-data-not-pulled-in-the-required