Difference between revisions of "SQL - Group several lines in the same column with LIST TAG"
Jump to navigation
Jump to search
(Created page with "<syntaxhighlight lang="sql"> select ost_pid_facility, listagg( ('COL: '||trim(mic_txt_mis_value)||' OST: '||trim(ost_nme_alias)) , ', ' ) WITHIN GROUP (ORDER BY ost_pid_f...") |
|||
(6 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
SQL : | |||
<syntaxhighlight lang="sql"> | <syntaxhighlight lang="sql"> | ||
SELECT country, | |||
listagg(first_name, ', ') WITHIN GROUP (order by first_name) | |||
FROM tablename | |||
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 | |||
) | ) | ||
WITHIN GROUP (ORDER BY | |||
from | 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); | |||
group by | |||
-- 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;