最近在做一新項目涉及到複雜的查詢,其中就包括需要將多行數據轉化爲一行顯示,在網上Google了一把然後自己改了一點就可以用了,記錄下來以爲後用.
第一步: 新建Types類型:
create or replace type combStrType as object
(
currentstr varchar2(4000),
currentseprator varchar2(8),
static function ODCIAggregateInitialize(sctx IN OUT combStrType) return number,
member function ODCIAggregateIterate(self IN OUT combStrType, value IN VARCHAR2) return number,
member function ODCIAggregateTerminate(self IN combStrType, returnValue OUT VARCHAR2, flags IN number) return number,
member function ODCIAggregateMerge(self IN OUT combStrType, ctx2 IN combStrType) return number
);
create or replace type body combStrType is
static function ODCIAggregateInitialize(sctx IN OUT combStrType)
return number is
begin
sctx := combStrType('',' / ');
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT combStrType, value IN VARCHAR2) return number is
begin
if self.currentstr is null then
self.currentstr := value;
else
self.currentstr := self.currentstr ||currentseprator || value;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN combStrType, returnValue OUT VARCHAR2, flags IN number) return number is
begin
returnValue := self.currentstr;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT combStrType, ctx2 IN combStrType) return number is
begin
if ctx2.currentstr is null then
self.currentstr := self.currentstr;
elsif self.currentstr is null then
self.currentstr := ctx2.currentstr;
else
self.currentstr := self.currentstr || currentseprator || ctx2.currentstr;
end if;
return ODCIConst.Success;
end;
end;
第二步:新建函數
CREATE OR REPLACE FUNCTION
combStr (input VARCHAR2) RETURN VARCHAR2
PARALLEL_ENABLE AGGREGATE USING combStrType;
第三步:查詢
SELECT tm_teamname,
combStr
(tm_subteam) FROM AS02TM
GROUP BY tm_teamname;
tm_teanname combStr (tm_subteam)
aaa A / B / C
bbb A / C
PS: oracle 10g 後提供了一個聚集函數 wm_concat 可以實現此類功能
SELECT tm_teamname, wm_concat(tm_subteam) FROM AS02TM GROUP BY tm_teamname;