Reputation: 1
Given a column of values ('Black', 'White', 'Orange') with sequence numbers 1,2,3 respectively, i need to find the permutations and combinations such as below.
Colortable Color Sequence
Black 1
White 2
Orange 3 ColorCombi table with 2 columns In NotIn
Black White, Orange
White Black, Orange
Orange Black, White
Black, White Orange
Black, Orange White
Orange, White Black
Black, White, Orange Null
Upvotes: 0
Views: 122
Reputation: 1269883
This is tricky to do. You can do it with a recursive CTE:
with t as (
select v.*
from (values ('Black', 1), ('White', 2), ('Orange', 3)) v(color, seq)
),
combos as (
select cast('' as varchar(max)) as ins, cast('' as varchar(max)) as outs, 0 as seq
union all
select c.ins + v.ins, c.outs + v.outs, c.seq + 1
from t cross apply
(values (',' + t.color, ''), ('', ',' + t.color)) as v(ins, outs) join
combos c
on t.seq = c.seq + 1
)
select top (1) with ties stuff(ins, 1, 1, '') as ins, stuff(outs, 1, 1, '') as outs
from combos
order by seq desc ;
Here is a db<>fiddle.
Upvotes: 1