oracle中多行聚合成字串

2021-05-21 19:07:12 字數 2625 閱讀 5843

create table t_row_str(

id int,

col varchar2(10));

insert into t_row_str values(1,'a');

insert into t_row_str values(1,'b');

insert into t_row_str values(1,'c');

insert into t_row_str values(2,'a');

insert into t_row_str values(2,'d');

insert into t_row_str values(2,'e');

insert into t_row_str values(3,'c');

commit;

select * from t_row_str;

5.1max + decode

適用範圍:

8i,9i,10g

及以後版本

select id,

max(decode(rn, 1, col, null)) ||

max(decode(rn, 2, ',' || col, null)) ||

max(decode(rn, 3, ',' || col, null)) str

from (select id,

col,

row_number() over(partition by id order by col) as rn

from t_row_str) t

group by id

order by 1;

5.2row_number + lead

適用範圍:

8i,9i,10g

及以後版本

select id, str

from (select id,

row_number() over(partition by id order by col) as rn,

col || lead(',' || col, 1) over(partition by id order by col) ||

lead(',' || col, 2) over(partition by id order by col) ||

lead(',' || col, 3) over(partition by id order by col) as str

from t_row_str)

where rn = 1

order by 1;

5.3model

適用範圍:

10g及以後版本

select id, substr(str, 2) str from t_row_str

model

return updated rows

partition by(id)

dimension by(row_number() over(partition by id order by col) as rn)

measures (cast(col as varchar2(20)) as str)

rules upsert

iterate(3) until( presentv(str[iteration_number+2],1,0)=0)

(str[0] = str[0] || ',' || str[iteration_number+1])

order by 1;

5.4sys_connect_by_path

適用範圍:

8i,9i,10g

及以後版本

select t.id id, max(substr(sys_connect_by_path(t.col, ','), 2)) str

from (select id, col, row_number() over(partition by id order by col) rn

from t_row_str) t

start with rn = 1

connect by rn = prior rn + 1

and id = prior id

group by t.id;

適用範圍:

10g及以後版本

select t.id id, substr(sys_connect_by_path(t.col, ','), 2) str

from (select id, col, row_number() over(partition by id order by col) rn

from t_row_str) t

where connect_by_isleaf = 1

start with rn = 1

connect by rn = prior rn + 1

and id = prior id;

5.5wmsys.wm_concat

適用範圍:

10g及以後版本

這個函式預定義按

','分隔字串,若要用其他符號分隔可以用,

replace

將','

替換。select id, replace(wmsys.wm_concat(col), ',', '/') str

from t_row_str

group by id;

最長合成字串

題目描述 有一組單詞,請編寫乙個程式,在陣列中找出由陣列中字串組成的最長的串a,即a是由其它單詞組成的 可重複 最長的單詞。給定乙個string陣列str,同時給定陣列的大小n。請返回最長單詞的長度,保證題意所述的最長單詞存在。測試樣例 a b c ab bc abc 6 返回 3 class lo...

多行字串 模板字串

多行字串 下面是普通字串的寫法 普通字串 var l abcd console.log l 編譯結果 如何讓讓乙個字串獨佔多行呢?就需要用到es6 裡的多行字串 多行字串 var i ab cd console.log i 編譯結果 再說說拼接字串,一般情況我們是如何拼接字串的呢?看下面 正常拼接字...

python多行字串

python中如何處理長 格式化問題,如何提高格式化輸出的長字串的可讀性?當我們需要格式化輸出乙個很長的字串的時候,都寫在一行顯得很難看,而且可讀性也很差 當我們使用鏈式的語法寫 的時候常常會超出螢幕的顯示區域。很多語言都有這方面的支援,但是python出現之後,無人能出其右,與其媲美。下面我們看看...