Home Forums Programming General Cte for String in random order RE: Cte for String in random order

  • Building off of Sean's idea - this gives you the same functionality with up to 6 words

    Note: since the number of permutations will grow factorially as you expand the number of possible words in a given set, scale at your own risk.

    declare @SomeString varchar(50) = 'tesco mixed fruit bob joe frank'

    ;with

    shortTally as (select top 6 Row_number() over (order by (select null)) n from sys.columns),

    SplitValues as

    (

    select Row_number() over (order by (select null)) TokenID, s.Item

    from dbo.DelimitedSplit8K(@SomeString, ' ') s

    ),

    TokenCount as (select SUM(n) C from shortTally where n<= (select COUNT(item) from SplitValues)),

    Cartesian as (

    select T1.n N1,

    case when c>1 then T2.n else 0 end n2,

    case when c>3 then T3.n else 0 end n3,

    case when c>6 then T4.n else 0 end n4,

    case when c>10 then T5.n else 0 end n5,

    case when c>15 then T6.n else 0 end n6

    from shortTally T1

    join shortTally t2 on T1.n<>t2.n

    join shortTally t3 on t1.n<>t3.n and t2.n<>t3.n

    join shortTally t4 on t1.n<>t4.n and t2.n<>t4.n and t3.n<>t4.n

    join shortTally t5 on t1.n<>t5.n and t2.n<>t5.n and t3.n<>t5.n and t4.n<>t5.n

    join shortTally t6 on t1.n<>t6.n and t2.n<>t6.n and t3.n<>t6.n and t4.n<>t6.n and t5.n<>t6.n

    cross join tokencount

    )

    select s1.item+

    coalesce(' '+s2.item,'')+

    coalesce(' '+s3.item,'')+

    coalesce(' '+s4.item,'')+

    coalesce(' '+s5.item,'')+

    coalesce(' '+s6.item,'')

    from Cartesian

    left join SplitValues s1 on N1=s1.TokenID

    left join SplitValues s2 on N2=s2.TokenID

    left join SplitValues s3 on N3=s3.TokenID

    left join SplitValues s4 on N4=s4.TokenID

    left join SplitValues s5 on N5=s5.TokenID

    left join SplitValues s6 on N6=s6.TokenID

    where N1+n2+n3+n4+n5+n6 = (select C from TokenCount)

    ----------------------------------------------------------------------------------
    Your lack of planning does not constitute an emergency on my part...unless you're my manager...or a director and above...or a really loud-spoken end-user..All right - what was my emergency again?