如何在Oracle中获得相似的价值

时间:2019-03-24 07:05:25

标签: mysql oracle

我有两列的表

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

我需要的输出是这样

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

谢谢。

2 个答案:

答案 0 :(得分:4)

这是一个适用于MySQL的解决方案。它在select子句中使用相关的子查询将Col2值组合在一起。逻辑是,对于给定的共享相同Col1值的记录组,我们只汇总小于或等于当前行的值。

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

这是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

请注意,唯一真正的变化是将LISTAGG替换为GROUP_CONCAT

答案 1 :(得分: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.