Format rows into comma seperated string

Example 

select userid,company_name,remarks from visit_details where userid=786;

    USERID COMPANY_NAME                   REMARKS
---------- ------------------------------ ---------------------------------------
       786 abc                            xyz
       786 def                            uvw
       786 ghi                            pqr


The output requirement is 

       786 abc,def,ghi                    xyz,uvw,pqr


Solution

 select userid,
       (
       select listagg(company_name,',')  within group (order by company_name) 
       from visit_details where userid=786
       ) as company_name,      
       (
       select listagg(remarks,',')  within group (order by remarks) 
       from visit_details where userid=786
       ) as remarks
       from
       (
         select userid,collect(distinct company_name),collect(distinct remarks)
         from visit_details where userid=786 group by userid
         )  ;



 
    USERID COMPANY_NAME                   REMARKS
---------- ------------------------------ ---------------------------------------

       786 abc,def,ghi                    xyz,uvw,pqr


2)  On single column

select listagg(company_name,',')  within group (order by company_name) 
       from visit_details where userid=786  ;




COMPANY_NAME              
----------
abc,def,ghi                   

Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post