with test as (select rownum id, regexp_substr('1,2,3,4', '[^,]+',1,rownum) n from dual connect by rownum < 5) select case when end_out1=24 then '('||'('||n1||f1||n2||')'||f2||n3||')'||f3||n4||'='||'24' when end_out2=24 then '('||n1||f1||n2||')'||f3||'('||n3||f2||n4||')'||'='||'24' when end_out3=24 then n1||f3||'('||'('||n2||f1||n3||')'||f2||n4||')'||'='||'24' end from ( select x2.*,d.n n4,f3, decode(f3, '+', c123 + d.n, '-', c123 - d.n, '*', c123 * d.n, '/', c123 / d.n) end_out1, decode(f3, '+', c12 + decode(f2, '+', n3 + d.n, '-', n3 - d.n, '*', n3 * d.n, '/', n3 / d.n), '-', c12 - decode(f2, '+', n3 + d.n, '-', n3 - d.n, '*', n3 * d.n, '/', n3 / d.n), '*', c12 * decode(f2, '+', n3 + d.n, '-', n3 - d.n, '*', n3 * d.n, '/', n3 / d.n), '/', c12 / decode(f2, '+', n3 + d.n, '-', decode(n3,d.n,null,n3-d.n), '*', n3 * d.n, '/', n3 / d.n) ) end_out2, decode(f3, '+', n1 + decode(f2, '+', c23 + d.n, '-', c23 - d.n, '*', c23 * d.n, '/', c23 / d.n), '-', n1 - decode(f2, '+', c23 + d.n, '-', c23 - d.n, '*', c23 * d.n, '/', c23 / d.n), '*', n1 * decode(f2, '+', c23 + d.n, '-', c23 - d.n, '*', c23 * d.n, '/', c23 / d.n), '/', n1 / decode(f2, '+', decode(c23,-1*d.n,null,c23+d.n), '-', decode(c23,d.n,null,c23-d.n), '*', decode(c23,0,null,c23 * d.n), '/', decode(c23,0,null,c23 / d.n) )) end_out3 from (select id1,id2,c.id id3, x1.n1,x1.n2,c.n n3, f1,f2,x1.c12, decode(f2, '+', c12+ c.n, '-', c12 - c.n, '*', c12 * c.n, '/', c12 / c.n) c123, decode(f1, '+', n2+ c.n,'-', n2- c.n, '*', n2* c.n, '/', n2 / c.n) c23 from (select a.id id1,b.id id2, a.n n1, b.n n2, f1, decode(f1, '+', a.n + b.n, '-', a.n - b.n, '*', a.n * b.n, '/', a.n / b.n) c12 from test a, test b, (select substr('+-*/', rownum, 1) f1 from dual connect by rownum < 5) x where a.id <> b.id) x1, test c, (select substr('+-*/', rownum, 1) f2 from dual connect by rownum < 5) x where x1.id1 <> c.id and x1.id2 <> c.id)x2, test d, (select substr('+-*/', rownum, 1) f3 from dual connect by rownum < 5) x where id1<>d.id and id2<>d.id and id3<>d.id ) x3 where end_out1=24 or end_out2=24 or end_out3=24