Skip to content
Advertisement

Oracle SQL – create string by concatenating rows but does not exceed X number of characters

First I am trying to concatenate rows into string separated by comma. Second I do not want the string to be exceeded X number of character. If going to exceed then create another string from next row onward without slitting the character from each rows. I am trying to achieve this through oracle SQL.

I am looking at LISTAGG which give me the concatenated string but I have not idea how I can split by X number of characters without splitting a values from each rows, let’s say my X = 15 characters. What I get using the below code is

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20

My expected output will be,

row 1: 1,2,3,4,5,6,7,8 (15 characters)

row 2: 9,10,11,12,13 (13 characters because that going to exceed 15 if I add value from next row)

row 3: 14,15,16,17,18 (14 characters)

row 4: 19,20 (5 characters)

I am still not sure this can be achieved, any suggestion or hint will be most appreciated.

Advertisement

Answer

I tried the following query and achieved the desired result.

Output:

Output

db<>fiddle demo

Cheers!!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement