Jaa*_*nna 21 oracle plsql oracle11g plsqldeveloper
我有这样一张桌子(报告)
--------------------------------------------------
| user_id | Department | Position | Record_id |
--------------------------------------------------
| 1 | Science | Professor | 1001 |
| 1 | Maths | | 1002 |
| 1 | History | Teacher | 1003 |
| 2 | Science | Professor | 1004 |
| 2 | Chemistry | Assistant | 1005 |
--------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
我想得到以下结果
---------------------------------------------------------
| user_id | Department+Position |
---------------------------------------------------------
| 1 | Science,Professor;Maths, ; History,Teacher |
| 2 | Science, Professor; Chemistry, Assistant |
---------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
这意味着我需要将空白空间保留为'',如您在结果表中看到的那样.现在我知道如何使用LISTAGG功能,但仅限于一列.但是,我无法弄清楚如何在同一时间对两列进行操作.这是我的查询:
SELECT user_id, LISTAGG(department, ';') WITHIN GROUP (ORDER BY record_id)
FROM report
Run Code Online (Sandbox Code Playgroud)
提前致谢 :-)
Ben*_*Ben 33
它只需要在聚合中明智地使用连接:
select user_id
, listagg(department || ',' || coalesce(position, ' '), '; ')
within group ( order by record_id )
from report
group by user_id
Run Code Online (Sandbox Code Playgroud)
即department使用逗号聚合连接,如果为空,则用空格position替换position.