I want to replace the below query using XMLAGG function and also eliminate the distinct logic.
SELECT
listagg(distinct OD.PROD_NAME,';') within group(order by SC.CATEGORY_ID) as PRODUCT
FROM
orders OD,
SERVICES SC
I tried to refer below query but couldn't understand
select
deptno,
rtrim (xmlagg (xmlelement (e, ename || ',')).extract ('//text()'), ',') enames
from
emp
group by
deptno
;
You tagged the question with "Oracle 11g" tag; it doesn't support LISTAGG (DISTINCT...)
- distinct
was introduced in 19c so - if you aren't on that version (or higher), you can't use it.
What to do, then? Use a subquery to fetch distinct values you need, and the join it (the subquery) to another table.
Here's an example based on Scott's sample schema (as I don't have your tables):
SQL> SELECT LISTAGG (e.job, ';') WITHIN GROUP (ORDER BY d.deptno, e.job) result
2 FROM (SELECT DISTINCT deptno, job
3 FROM emp) e
4 JOIN dept d ON d.deptno = e.deptno;
RESULT
------------------------------------------------------------------------------------------------------------------------
CLERK;MANAGER;PRESIDENT;ANALYST;CLERK;MANAGER;CLERK;MANAGER;SALESMAN
SQL>
SQL>
SQL> SELECT RTRIM (
2 XMLAGG (XMLELEMENT (e, e.job || ';') ORDER BY d.deptno, e.job).EXTRACT (
3 '//text()'),
4 ';') result
5 FROM (SELECT DISTINCT deptno, job
6 FROM emp) e
7 JOIN dept d ON d.deptno = e.deptno;
RESULT
------------------------------------------------------------------------------------------------------------------------
CLERK;MANAGER;PRESIDENT;ANALYST;CLERK;MANAGER;CLERK;MANAGER;SALESMAN
SQL>
Or, one below another (for better visibility):
LISTAGG: CLERK;MANAGER;PRESIDENT;ANALYST;CLERK;MANAGER;CLERK;MANAGER;SALESMAN
XMLAGG : CLERK;MANAGER;PRESIDENT;ANALYST;CLERK;MANAGER;CLERK;MANAGER;SALESMAN
As you can see, both return the same result.
Can I suggest a query for your case? Nope; as I said, I don't have your tables and I have no idea how orders
and services
are related to each other.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.