How to get a similar value in Oracle

前端 未结 2 1417
春和景丽
春和景丽 2021-01-28 09:00

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



        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 09:11

    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;
    

    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.

提交回复
热议问题