需要TSQL帮助才能从文本中创建所有可能的组合。
我有如下数据
Input
A
B
C
需要如下结果
Output
ABC
BCA
CAB
CBA
BAC
ACB
你可以使用join
:
select i1.col, i2.col, i3.col
from input i1 join
input i2
on i2.col not in (i1.col) join
input i3
on i3.col not in (i1.col, i2.col);
Here是这个解决方案的rextester。
编辑:
在我看来,你可能想要改变input
的长度,并且你真的想要所有排列的字符串。
如果是这样,可以使用递归CTE处理:
with input as (
select v.x
from (values ('a'), ('b'), ('c')) v(x)
),
cte as (
select cast(x as varchar(max)) as str, 1 as len
from input
union all
select cte.str + i.x, len + 1
from cte join
input i
on cte.str not like '%' + i.x + '%'
)
select top (1) with ties str
from cte
order by len desc;
Here是这个解决方案的SQL小提琴。
我认为cross可以产生所有可能的组合
select t2.c+t3.col from
(select t1.col+t2.col as c
from t t1 cross join
t t2
) as t2 cross join
t t3
https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=7a22b3c1f5fe81be1e2f3ec09311bd87