zoukankan      html  css  js  c++  java
  • oracle:自定义多行合并聚合函数

    原始表
    COUNTRY    CITY            
    -------------------- --------------
    中国        台北             
    中国        香港             
    中国        上海             
    日本        东京             
    日本        大阪             
     
    查询结果

    COUNTRY    CITY
    -------------------- ---------------
    中国        台北 香港 上海
    日本        东京 大阪

    select country,strcat(city) from t_city group by country;

    1.创建类型

    create or replace type strcat_type as object
    (
      cat_string varchar2(4000),
      static function ODCIAggregateInitialize(cs_ctx In Out strcat_type)
        return number,
      member function ODCIAggregateIterate(self  In Out strcat_type,
                                           value in varchar2) return number,
      member function ODCIAggregateMerge(self In Out strcat_type,
                                         ctx2 In Out strcat_type) return number,
      member function ODCIAggregateTerminate(self        In Out strcat_type,
                                             returnValue Out varchar2,
                                             flags       in number)
        return number
    );

    2. 创建类型体

    create or replace type body strcat_type is
      static function ODCIAggregateInitialize(cs_ctx IN OUT strcat_type)
        return number is
      begin
        cs_ctx := strcat_type(null);
        return ODCIConst.Success;
      end;
    
      member function ODCIAggregateIterate(self  IN OUT strcat_type,
                                           value IN varchar2) return number is
      begin
        self.cat_string := self.cat_string || ';' || value;
        return ODCIConst.Success;
      end;
    
      member function ODCIAggregateTerminate(self        IN Out strcat_type,
                                             returnValue OUT varchar2,
                                             flags       IN number) return number is
      begin
        returnValue := ltrim(rtrim(self.cat_string, ';'), ';');
        return ODCIConst.Success;
      end;
    
      member function ODCIAggregateMerge(self IN OUT strcat_type,
                                         ctx2 IN Out strcat_type) return number is
      
      begin
        self.cat_string := self.cat_string || ';' || ctx2.cat_string;
        return ODCIConst.Success;
      end;
    end;

    3.创建函数

    CREATE OR REPLACE FUNCTION strcat(input varchar2) RETURN varchar2
      PARALLEL_ENABLE
      AGGREGATE USING strcat_type;
  • 相关阅读:
    hdu 5007 水题 (2014西安网赛A题)
    hdu 1698 线段树(成段替换 区间求和)
    poj 3468 线段树 成段增减 区间求和
    hdu 2795 公告板 (单点最值)
    UVaLive 6833 Miscalculation (表达式计算)
    UVaLive 6832 Bit String Reordering (模拟)
    CodeForces 124C Prime Permutation (数论+贪心)
    SPOJ BALNUM (数位DP)
    CodeForces 628D Magic Numbers (数位DP)
    POJ 3252 Round Numbers (数位DP)
  • 原文地址:https://www.cnblogs.com/yuanxianlai/p/3966281.html
Copyright © 2011-2022 走看看