How to write a query that does something similar to MySQL's GROUP_CONCAT in Oracle?

余生颓废 提交于 2019-11-27 08:25:34

问题


When I run the following SQL query in my Oracle database:

SELECT p.pkt_nazwa, 
       u.us_nazwa 
FROM   punkty p, 
       kategorie_uslug ku, 
       usluga u 
WHERE  ku.pkt_id = p.pktk_1_id 
       AND ku.us_id = u.usk_1_id 
ORDER  BY p.pkt_nazwa; 

I get the following output:

NAME                | SERVICE
--------------------|-------------------
Baita De Mario      | WC 
Baita De Mario      | Kuchnia
Baita De Mario      | Nocleg
Bistro-Cafe         | Bar
Bistro-Cafe         | Dyskoteka
Bistro-Cafe         | Kuchnia

How would I go about to get the following output?

NAME                | SERVICES
--------------------|-------------------
Baita De Mario      | WC, Kuchnia, Nocleg 
Bistro-Cafe         | Bar, Dyskoteka, Kuchnia

回答1:


SELECT p.pkt_nazwa AS name, wm_concat(u.us_nazwa) AS services
FROM   punkty p
JOIN   kategorie_uslug ku ON ku.pkt_id = p.pktk_1_id
JOIN   usluga u ON u.usk_1_id = ku.us_id
GROUP  BY p.pkt_nazwa
ORDER  BY p.pkt_nazwa;

wm_concat() function is present in most versions.
More about string aggregating in Oracle.




回答2:


Here's an article explaining some approaches to what you're trying to do in Oracle:

http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php

Note that if you're running 11g Release 2 then LISTAGG is the way to go.




回答3:


Since Oracle 11.2 this has become easier using listagg()

SELECT p.pkt_nazwa AS name, 
       listagg(u.us_nazwa) WITHIN GROUP (ORDER BY u.us_nazwa) AS services
FROM punkty p
  JOIN kategorie_uslug ku ON ku.pkt_id = p.pktk_1_id
  JOIN usluga u ON u.usk_1_id = ku.us_id
GROUP BY p.pkt_nazwa
ORDER BY p.pkt_nazwa;


来源:https://stackoverflow.com/questions/8232048/how-to-write-a-query-that-does-something-similar-to-mysqls-group-concat-in-orac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!