Home > Database > Mysql Tutorial > Oracle 11g 列转行listagg

Oracle 11g 列转行listagg

WBOY
Release: 2016-06-07 16:43:40
Original
1356 people have browsed it

在Oracle 11g之前列转行有些麻烦,11g之后,非常简单。现在有功能的业务是,有一张test的表记录的是单据的审批信息,id为审批信息

在Oracle 11g之前列转行有些麻烦,11g之后,非常简单。现在有功能的业务是,,有一张test的表记录的是单据的审批信息,id为审批信息的主键,sheet_id为外键,是单据的id,remark为审批的内容,在前端的列表页面上,要看到这个单据所有的审批信息,要显示在一个格子里面。

SQL> drop table test purge;
SQL> create table test
(
  id  number(10),
  sheet_id number(10),
  remark varchar2(50)
);
SQL> insert into test values(1,100,'审批意见1');
SQL> insert into test values(2,100,'审批意见2');
SQL> insert into test values(3,100,'审批意见3');
SQL> insert into test values(4,200,'同意1');
SQL> insert into test values(5,200,'同意2');
SQL> insert into test values(6,200,'同意3');
SQL> insert into test values(7,300,'回退1');
SQL> insert into test values(8,300,'回退2');
SQL> commit;


SQL> col C_REMARK format a40;
SQL> select sheet_id,listagg(remark,',') within GROUP (order by id) as c_remark
    from test
    group by sheet_id;
  SHEET_ID C_REMARK
---------- ----------------------------------------
      100 审批意见1,审批意见2,审批意见3
      200 同意1,同意2,同意3
      300 回退1,回退2 

还有一种写法:

SQL> select sheet_id, listagg(remark, ',') within
    GROUP(
    order by id) over(partition by sheet_id) c_remark
      from test;
  SHEET_ID C_REMARK
---------- ----------------------------------------
      100 审批意见1,审批意见2,审批意见3
      100 审批意见1,审批意见2,审批意见3
      100 审批意见1,审批意见2,审批意见3
      200 同意1,同意2,同意3
      200 同意1,同意2,同意3
      200 同意1,同意2,同意3
      300 回退1,回退2
      300 回退1,回退2

SQL> select distinct sheet_id, listagg(remark, ',') within
    GROUP(
    order by id) over(partition by sheet_id) c_remark
      from test;
  SHEET_ID C_REMARK
---------- ----------------------------------------
      200 同意1,同意2,同意3
      100 审批意见1,审批意见2,审批意见3
      300 回退1,回退2

Oracle 11g 新聚集函数listagg实现列转行

本文永久更新链接地址:

linux

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template