• Oracle之多行记录变一行记录,行变列,并排序(wmsys.wm_concat)


    wmsys.wm_concat

    Definition: The Oracle PL/SQL WM_CONCAT function is used to aggregate data from a number of rows into a single row, giving a list of data associated with a specific COMMENT_BODY. In effect, it cross-tabulates a comma delimited list.

    Note that WM_CONCAT is undocumented and unsupported by Oracle, meaning it should not be used in production systems. The LISTAGG function, which can produce the same output asWM_CONCAT is both documented and supported by Oracle.

    1. 现有数据结构

    BBSDETAIL表(主表)

    DETAIL_ID NOT NULL NUMBER  主键
    TITLE NOT NULL VARCHAR2(100)

    BBSCOMMENT表(从表)

    DETAIL_ID NOT NULL NUMBER  外键
    COMMENT_BODY NOT NULL VARCHAR2(500)
    COMMENT_TIME NOT NULL DATE

    2. 实现功能一(从表多行记录合并为一行,不要求排序)

    --多行合并为一行,不要求排序
    select DETAIL_ID,wmsys.wm_concat('{'||COMMENT_BODY||'}')
    from BBSCOMMENT
    group by DETAIL_ID;

    输出:
    13859 {东西好,送货快 },{好 },{物流有些慢 }
    14938 {卖家还是挺热心的,以后再来 },{东西不错 }

    3. 实现功能二(从表多行记录合并为一行后,与主表做一连接)

    --将上述SQL语句与主表做一个连接查询
    select bd.DETAIL_ID,TITLE,bcm.COMMENT_INFO
    from BBSDETAIL bd,(select DETAIL_ID,wmsys.wm_concat('{'||COMMENT_BODY||'}') as COMMENT_INFO from BBSCOMMENT group by DETAIL_ID) bcm
    where bd.DETAIL_ID=bcm.DETAIL_ID(+);

    输出:
    13859 苏泊尔电压力锅配件 {东西好,送货快 },{好 },{物流有些慢 }
    14938 Nike/耐克男性跑步鞋跑步 {卖家还是挺热心的,以后再来 },{东西不错 }

    4. 实现功能三(从表多行记录合并为一行,并按评价时间排序)

    --多行合并为一行,要求排序(最新的评论在前面)
    select DETAIL_ID, max(r)
    from (select DETAIL_ID, wmsys.wm_concat(COMMENT_BODY||'('||to_char(COMMENT_TIME,'yyyy-mm-dd hh:mi:ss')||')')
        OVER(PARTITION BY DETAIL_ID ORDER BY COMMENT_TIME desc) r from BBSCOMMENT)
    group by DETAIL_ID;

    输出:

    13859 东西好,送货快(2013-02-19 06:27:37),好(2012-01-14 02:23:46),物流有些慢(2012-01-01 12:00:25)
    14938 卖家还是挺热心的,以后再来(2011-11-27 05:28:27),东西不错(2011-10-11 05:09:06)

    5. 实现功能四(行变列:分两列显示从表两种汇总结果,排序,并保证两列中数据的对应关系)

    --分两列显示两种汇总结果,并排序,保证对应关系
    select DETAIL_ID,COMMENT_TIME,COMMENT_BODY from (
     select
     DETAIL_ID,
      WMSYS.WM_CONCAT(to_char(COMMENT_TIME,'yyyy-mm-dd hh:mi:ss'))
              OVER(PARTITION BY DETAIL_ID ORDER BY COMMENT_TIME) COMMENT_TIME,
       WMSYS.WM_CONCAT('{'||COMMENT_BODY||'}')
              OVER(PARTITION BY DETAIL_ID ORDER BY COMMENT_TIME) COMMENT_BODY,
          row_number() OVER(PARTITION BY DETAIL_ID ORDER BY COMMENT_TIME desc) rs
      from BBSCOMMENT) where rs=1;

    输出:

    13859 2013-02-19 06:27:37,2012-01-14 02:23:46,2012-01-01 12:00:25 {东西好,送货快},{好},{物流有些慢}
    14938 2011-11-27 05:28:27,2011-10-11 05:09:06 {卖家还是挺热心的,以后再来},{东西不错}

  • 相关阅读:
    mysql8下载安装及配置
    jdk11下载安装及环境变量配置
    展示所有商品案例
    事务(转账实例)
    Part2.7 ESLint
    Part2.6 Webpack
    Part2.5 模块化开发
    Part2.4 gulp 实践
    Part2.3 Grunt
    Part2.2 plop 使用
  • 原文地址:https://www.cnblogs.com/nayitian/p/3231734.html
Copyright © 2020-2023  润新知