with recursive t as (select n from range(1,4+1) t(n)),
a(lv,c,s) as(select 1,n c,n::varchar s from t
union all
select lv+1,n,s||','||n::varchar from t,a where lv<3 and c&n!=0)
select * from a where lv==3;
│ lv │ c │ s │
------------------
│ 3│ 1 │ 1,1,1 │
│ 3│ 1 │ 3,1,1 │
│ 3│ 1 │ 1,3,1 │
│ 3│ 1 │ 2,3,1 │
│ 3│ 1 │ 3,3,1 │
│ 3│ 2 │ 2,2,2 │
│ 3│ 2 │ 3,2,2 │
│ 3│ 2 │ 1,3,2 │
│ 3│ 2 │ 2,3,2 │
│ 3│ 2 │ 3,3,2 │
│ 3│ 3 │ 1,1,3 │
│ 3│ 3 │ 3,1,3 │
│ 3│ 3 │ 2,2,3 │
│ 3│ 3 │ 3,2,3 │
│ 3│ 3 │ 1,3,3 │
│ 3│ 3 │ 2,3,3 │
│ 3│ 3 │ 3,3,3 │
│ 3│ 4 │ 4,4,4 │
|