Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top