Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat SQL Oracle Column into a string

I have a table below and would like to convert into below result into a string

table_name: employee_tb

    employee_id             employee_type
         1                        A
         2                        A
         3                        B
         4                        C
         5                        C
         6                        C

This is what I have so far

select employee_type, count(*) as employee_type_count from employee_tb
GROUP BY employee_type;  

The result I got is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 employee_type        employee_type_count
      A                       2
      B                       1
      C                       3

I would like to convert to below result. Is it possible?

result: A: 2, B: 1 C: 3

Thanks

>Solution :

You can use LISTAGG here to concatenate the employee_type and employee_type_count:

SELECT LISTAGG(employee_type || ': ' || employee_type_count, ', ') WITHIN GROUP (ORDER BY employee_type) AS result
FROM (
    SELECT employee_type, COUNT(*) AS employee_type_count
    FROM employee_tb
    GROUP BY employee_type
) subquery;

Here is workplace with my query using LISTAGG db query

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading