The most elegant way to generate permutations in SQL server

后端 未结 10 1384
面向向阳花
面向向阳花 2020-11-29 07:00

Given a the following table:

Index | Element
---------------
  1   |    A
  2   |    B
  3   |    C
  4   |    D

We want to generate all th

10条回答
  •  感动是毒
    2020-11-29 07:11

    Current solution using a recursive CTE.

    -- The base elements
    Declare @Number Table( Element varchar(MAX), Id varchar(MAX) )
    Insert Into @Number Values ( 'A', '01')
    Insert Into @Number Values ( 'B', '02')
    Insert Into @Number Values ( 'C', '03')
    Insert Into @Number Values ( 'D', '04')
    
    -- Number of elements
    Declare @ElementsNumber int
    Select  @ElementsNumber = COUNT(*)
    From    @Number;
    
    
    
    -- Permute!
    With Permutations(   Permutation,   -- The permutation generated
                         Ids,            -- Which elements where used in the permutation
                         Depth )         -- The permutation length
    As
    (
        Select  Element,
                Id + ';',
                Depth = 1
        From    @Number
        Union All
        Select  Permutation + ' ' + Element,
                Ids + Id + ';',
                Depth = Depth + 1
        From    Permutations,
                @Number
        Where   Depth < @ElementsNumber And -- Generate only the required permutation number
                Ids Not like '%' + Id + ';%' -- Do not repeat elements in the permutation (this is the reason why we need the 'Ids' column) 
    )
    Select  Permutation
    From    Permutations
    Where   Depth = @ElementsNumber
    

提交回复
热议问题