Search code examples
sqloracle-databasestring-aggregation

How to set record in one line after Group By


I want to set all record in one line with seperated by , after GroupBy

My input:

+ --------- + -------------- +
| Name      | Phone Number   |
+ --------- + -------------- +
| John      | 1234567        |
| John      | 1472583        |
| John      | 3698521        |
| John      | 7896541        |
+ --------- + -------------- +

Output I want

+ --------- + -------------------------------+
| Name      |           Phone Number         |
+ --------- + -------------------------------+
| John      | 1234567,1472583,3698521,7896541|
+ --------- + -------------------------------+

Solution

  • You are looking for listagg():

    select name, listagg(phone_number, ', ') within group (order by phone_number) as phone_numbers
    from t
    group by name;