0

I have a table of two columns

Col1  Col2
A        1
A        2
A        3
B        1
B        2
B        3

Output I need is like this

Col1    Col2
A       1
A       1,2
A       1,2,3
B       1
B       1,2
B       1,2,3

Thank you in advance.

2
  • 1
    Which database are you actually using, MySQL or Oracle? They're not the same thing. Mar 24, 2019 at 7:07
  • @TimBiegeleisen It for learn purpose. I need to know in both but mostly in oracle. Mar 24, 2019 at 7:16

2 Answers 2

4

Here is a solution which would work for MySQL. It uses a correlated subquery in the select clause to group concatenate together Col2 values. The logic is that we only aggregate values which are less than or equal to the current row, for a given group of records sharing the same Col1 value.

SELECT
    Col1,
    (SELECT GROUP_CONCAT(t2.Col2 ORDER BY t2.Col2) FROM yourTable t2
     WHERE t2.Col2 <= t1.Col2 AND t1.Col1 = t2.Col1) Col2
FROM yourTable t1
ORDER BY
    t1.Col1,
    t1.Col2;

enter image description here

Demo

Here is the same query in Oracle:

SELECT
    Col1,
    (SELECT LISTAGG(t2.Col2, ',') WITHIN GROUP (ORDER BY t2.Col2) FROM yourTable t2
     WHERE t2.Col2 <= t1.Col2 AND t1.Col1 = t2.Col1) Col2
FROM yourTable t1
ORDER BY
    t1.Col1,
    t1.Col2;

Demo

Note that the only real change is substituting LISTAGG for GROUP_CONCAT.

0
with s (Col1, Col2) as (
select 'A', 1 from dual union all
select 'A', 2 from dual union all
select 'A', 3 from dual union all
select 'B', 1 from dual union all
select 'B', 2 from dual union all
select 'B', 3 from dual)
select col1, ltrim(sys_connect_by_path(col2, ','), ',') path
from s
start with col2 = 1
connect by prior col2 = col2 - 1 and prior col1 = col1;

C PATH
- ----------
A 1
A 1,2
A 1,2,3
B 1
B 1,2
B 1,2,3

6 rows selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.