Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Multiple Values comma separated when using GROUP BY [duplicate]

I have data that looks like

CUSTOMER,  CUSTOMER_ID, PRODUCT
ABC INC    1            XYX
ABC INC    1            ZZZ
DEF CO     2            XYX
DEF CO     2            ZZZ
DEF CO     2            WWW
GHI LLC    3            ZYX

I'd like to write a query that'd make the data look like this:

CUSTOMER, CUSTOMER_ID, PRODUCTS
ABC INC   1            XYX, ZZZ
DEF CO    2            XYX, ZZZ, WWW
GHI LLC   3            ZYX

Using Oracle 10g if helps. I saw something that would work using MYSQL, but I need a plain SQL or ORACLE equivalent. I've also seen examples of stored procs that could be made, however, I cannot use a stored proc with the product i'm using.

Here's how'd it work in MySQL if I were using it

SELECT CUSTOMER, 
       CUSTOMER_ID, 
       GROUP_CONCAT( PRODUCT ) 
FROM MAGIC_TABLE 
GROUP BY CUSTOMER, CUSTOMER_ID

Thank you.

like image 606
Roy Rico Avatar asked Oct 24 '08 17:10

Roy Rico


2 Answers

I think LISTAGG is the best aggregate group by function to use in this situation:

  SELECT CUSTOMER, CUSTOMER_ID,
         LISTAGG(PRODUCT, ', ') WITHIN GROUP (ORDER BY PRODUCT)
    FROM SOME_TABLE
GROUP BY CUSTOMER, CUSTOMER_ID
ORDER BY 1, 2
like image 184
ScrappyDev Avatar answered Oct 03 '22 07:10

ScrappyDev


This link refers to a number of examples of different ways to do this on Oracle. See if there's something there that you have permissions on your database to do.

like image 33
ConcernedOfTunbridgeWells Avatar answered Oct 03 '22 07:10

ConcernedOfTunbridgeWells