zoukankan      html  css  js  c++  java
  • Oracle通用行转列方法,适合报表统计等

    create or replace function row_to_col_func(tabname in varchar2,--tabname 需要进行行转列操作的表名;
                                      group_col in varchar2,--group_col 查询结果要按某列或某些列分组的字段名;
                                      column_col in varchar2,--column_col 要从行转成列的字段;;
                                      value_col in varchar2,--value_col 需要聚合的值字段;
                                      Aggregate_func in varchar2 default 'max',--Aggregate_func 选用的聚合函数,可选,默认为max;
                                      colorder in varchar2 default null,--colorder 行转列后列的排序,可选;
                                      roworder in varchar2 default null,--roworder 行转列后记录的排序,可选;
                                      when_value_null in varchar2 default null--when_value_null 若value_col字段的值聚合后为空,则转换成该值,可选;
                                      )return sys_refcursor
    Authid Current_User
    as
      sqlstr varchar2(2000):='select '||group_col||' ';
      c1 sys_refcursor;
      v1 varchar2(100);
      cur sys_refcursor;
    begin
      open c1 for 'select distinct '||column_col||' from '||tabname||case when colorder is not null then ' order by '||colorder end;
      loop
        fetch c1 into v1;
        exit when c1%notfound;
        sqlstr:=sqlstr||chr(10)||','||case when when_value_null is not null then 'nvl(' end||
          Aggregate_func||'(decode(to_char('||column_col||'),'''||v1||''','||value_col||'))'||
          case when when_value_null is not null then chr(44) ||when_value_null||chr(41) end||'"'||v1||'"';
      end loop;
      close c1;
      open cur for sqlstr||' from '||tabname||' group by '||group_col||case when roworder is not null then ' order by '||roworder end;
      return cur;
    end row_to_col_func;

    select row_to_col_func
    ('rowtocol_test','year,month','dept','expenditure','sum','dept','1,2','0') from dual;  

  • 相关阅读:
    Xcode11 Developer Tool中没了Application Loader
    iOS
    iOS
    UIView与CALayer的区别,很详细(基础教学拓展)转
    使pre的内容自动换行(转)小知识
    requirejs:模块加载(require)及定义(define)时的路径理解
    JS国际化网站中英文切换(理论支持所有语言)应用于h5版APP
    Tomcat8 配置APR模式
    Mongodb安装
    SecureCRT配色方案
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234352.html
Copyright © 2011-2022 走看看