Skip to content
Advertisement

Oracle SQL: how to concatenate text until reaches maximum size

I have a case:

some script to reproduce:

And Select:

What i want to achieve is concatenate texts until sum of them is less than 3000. If larger, then another text.

And here goes problem: texts with group 1 when You sum them is greater than 3000. Text with id = 2 supposed to have group 2 but is 1.

Anyone has an idea? Thanks

Advertisement

Answer

From Oracle 12, you can use MATCH_RECOGNIZE:

Which, for your sample data, outputs:

ID TEXT_LEN MATCH_NUM TOTAL_LEN
1 1039 0 2078
2 1039 0 2078
3 1039 1 2078
4 1039 1 2078
5 1039 2 2078
6 1039 2 2078

db<>fiddle here

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