【问题标题】:LISTAGG function with two columns具有两列的 LISTAGG 函数
【发布时间】:2012-12-02 08:14:58
【问题描述】:

我有一张这样的桌子(报告)

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

提前致谢:-)

【问题讨论】:

    标签: oracle plsql oracle11g plsqldeveloper


    【解决方案1】:

    它只需要在聚合中明智地使用串联:

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

    即用逗号聚合departmentposition 的连接,如果position 为NULL,则用空格替换。

    【讨论】:

    • 喜欢 5 年后更新的评论。 NVL 是邪恶用途:合并 stackoverflow.com/a/18750233/458741 +1 以改进旧版答案。
    • 缺少 group by 子句
    • 谢谢@gauti;我已经修好了。 6 年来没有人(包括我)注意到这一点有点惊讶!
    • 太棒了。感谢您考虑@Ben!
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2012-02-29
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多