martes, 30 de abril de 2024

[SQL] LISTAGG Function

Sometimes, I'm find needing go group data grouping by a line. For example, how get and export all user emails. Normally, we have 1-1 relation a database table, but we want export grouping un a unique line by user. I'm sure, we could export to a excel and pivot in a table, or with other tool. But, how to do it in SQL?

The solution lies in the LISTAGG function, which groups all rows results into a single colum.

The sintax is the next:

           
SELECT LISTAGG(column_name, delimiter) WITHIN GROUP (ORDER BY ordering_column)
FROM table_name

        

Consequently, in the previous example, we could achieve this with the following query:

SELECT EAAN8, ABALPH, LISTAGG(TRIM(EAEMAL), ',') WITHIN GROUP (ORDER BY EAEMAL) AS EMAILS FROM F01151 JOIN F0101 ON EAAN8=ABAN8 WHERE EAETP = 'E' GROUP BY EAAN8, ABALPH;

Return the nex ouptut:


In next posts we are looking how export in XML, JSON, etc. format.

Kind regards and good code!


No hay comentarios:

Publicar un comentario