Let's start with a constant 3 instead of :n.
The sum of consecutive integers from 1 through n can be calculated as n(n+1)/2. This gives me the number of rows to generate:
select level S
from dual
connect by level <= 3 * (3 +1) / 2;
S
----------
1
2
3
4
5
6
Now what I need is to calculate n based on the value of S. With a little help from my son, I found the formula n = (sqrt(8*S+1)-1)/2.
select level S,
(sqrt(8*level+1)-1)/2 n
from dual
connect by level <= 3 * (3 +1) / 2;
S N
---------- ----------
1 1
2 1.56155281
3 2
4 2.37228132
5 2.70156212
6 3
If we round that up, what we get is actually the
previous "n+1"
select level S,
ceil((sqrt(8*level+1)-1)/2) "Prev n+1"
from dual
connect by level <= 3 * (3 +1) / 2;
S Prev n+1
---------- ----------
1 1
2 2
3 2
4 3
5 3
6 3
So now we can calculate the previous "n(n+1)/2". We subtract that from our current S and we get a remainder, which is our answer.
select level S,
ceil((sqrt(8*level+1)-1)/2) "Prev n+1",
ceil((sqrt(8*level+1)-1)/2)-1 "Prev n",
ceil((sqrt(8*level+1)-1)/2) * (ceil((sqrt(8*level+1)-1)/2)-1)/2 "Prev n(n+1)/2",
level - ceil((sqrt(8*level+1)-1)/2) * (ceil((sqrt(8*level+1)-1)/2)-1)/2 "S - Prev n(n+1)/2"
from dual
connect by level <= 3 * (3 +1) / 2;
S Prev n+1 Prev n Prev n(n+1)/2 S - Prev n(n+1)/2
---------- ---------- ---------- ------------- -----------------
1 1 0 0 1
2 2 1 1 1
3 2 1 1 2
4 3 2 3 1
5 3 2 3 2
6 3 2 3 3
Best regards, Stew