给出一列分别为序列号1,2,3的值(“黑色”,“白色”,“橙色”),我需要找到如下排列和组合。
颜色表颜色顺序
黑色1
白色2
在NotIn中有2列的橙色3 ColorCombi表
黑白色,橙色
白色黑色,橙色
橙色黑色,白色
黑色,白色橙色
黑色,橙色白色
橙色,白色黑色
黑色,白色,橙色为空
答案 0 :(得分:1)
这很棘手。您可以使用递归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是db <>小提琴。