LISTAGG功能有两列

时间:2012-12-14 10:26:16

标签: 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     |
--------------------------------------------------

我想得到以下结果

   ---------------------------------------------------------
   | user_id  |  Department+Position                       |
   ---------------------------------------------------------
   |  1       | Science,Professor;Maths, ; History,Teacher |
   |  2       | Science, Professor; Chemistry, Assistant   |
   ---------------------------------------------------------

这意味着我需要将空白空间保留为'',如结果表中所示。 现在我知道如何使用LISTAGG功能,但仅限于一列。但是,我无法弄清楚如何在同一时间对两列进行操作。这是我的疑问:

SELECT user_id, LISTAGG(department, ';') WITHIN GROUP (ORDER BY record_id)
FROM report

提前致谢: - )

1 个答案:

答案 0 :(得分:29)

它只需要在聚合中明智地使用连接:

select user_id
     , listagg(department || ',' || coalesce(position, ' '), '; ')
        within group ( order by record_id )
  from report
 group by user_id

即。汇总department与逗号和position的连接,并将position替换为空格(如果为空)。