Difference between revisions of "SQL - Group several lines in the same column with LIST TAG"
Jump to navigation
Jump to search
(4 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
SQL : | |||
<syntaxhighlight lang="sql"> | <syntaxhighlight lang="sql"> | ||
SELECT country, | SELECT country, | ||
Line 4: | Line 5: | ||
FROM tablename | FROM tablename | ||
GROUP BY country | GROUP BY country | ||
</syntaxhighlight> | |||
SQL v2 workaround for "too long string column concatenation issue" : | |||
<syntaxhighlight lang="sql"> | |||
with PRECALC as ( | |||
select floor(4000/(max(length(MY_COLUMN)+LENGTH(',')))) as MAX_FIELD_LENGTH | |||
from MY_TABLE | |||
) | |||
select | |||
LISTAGG(MY_COLUMN,',') WITHIN GROUP(ORDER BY floor(rownum/MAX_FIELD_LENGTH), MY_COLUMN) | |||
from MY_TABLE, PRECALC | |||
group by floor(rownum/MAX_FIELD_LENGTH); | |||
-- OR | |||
select listagg(product_name, ',' on overflow truncate) within group (order by product_name) | |||
from products; | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 15:53, 8 October 2021
SQL :
SELECT country,
listagg(first_name, ', ') WITHIN GROUP (order by first_name)
FROM tablename
GROUP BY country
SQL v2 workaround for "too long string column concatenation issue" :
with PRECALC as (
select floor(4000/(max(length(MY_COLUMN)+LENGTH(',')))) as MAX_FIELD_LENGTH
from MY_TABLE
)
select
LISTAGG(MY_COLUMN,',') WITHIN GROUP(ORDER BY floor(rownum/MAX_FIELD_LENGTH), MY_COLUMN)
from MY_TABLE, PRECALC
group by floor(rownum/MAX_FIELD_LENGTH);
-- OR
select listagg(product_name, ',' on overflow truncate) within group (order by product_name)
from products;