Concat 2列数据通过另一列(group by)

时间:2014-03-06 07:05:18

标签: sql oracle concat

我的表 - 教育

State    Code   Descr

AA       001    aaaaaa
AA       002    aaaabbb
BB       003    qwerty
CC       025    asdfg
BB       014    zsedc
AA       015    lknhj
CC       084    uhygt
CC       067    fdrda

我希望它采用以下格式:

州代码

AA       001-aaaaaa,002-aaaabbb,015-lknhj

BB       003-qwerty,014-zsedc**

CC       025-asdfg,084-uhygt,067-fdrda

我正在尝试并成功通过以下查询获取单行“Code”:

select state,
replace(wm_concat(code), ',', ',') CODE
from education
group by state
order by state;

输出:

State    Code

AA       001,002,015

BB       003,014

CC       025,084,067

此外,我通过以下查询获得了每个descr各自的code

select state, concat(concat(replace(wm_concat(code),',',','), '-'),descr) CODE
from education
group by state,descr
order by state

你能帮助我解决问题,以获得所需的输出。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

这不帮忙吗?

select state,
replace(wm_concat(code||'-'||descr), ',', ',') CODE
from education
group by state
order by state;

如果是Oracle 11g,它可以是

select state,
LISTAGG(code||'-'||descr,',') (WITHIN GROUP ORDER BY code) as CODE
from education
group by state
order by state;