The most elegant way to generate permutations in SQL server

后端 未结 10 1363
面向向阳花
面向向阳花 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:30

    Just using SQL, without any code, you could do it if you can crowbar yourself another column into the table. Clearly you need to have one joined table for each of the values to be permuted.

    with llb as (
      select 'A' as col,1 as cnt union 
      select 'B' as col,3 as cnt union 
      select 'C' as col,9 as cnt union 
      select 'D' as col,27 as cnt
    ) 
    select a1.col,a2.col,a3.col,a4.col
    from llb a1
    cross join llb a2
    cross join llb a3
    cross join llb a4
    where a1.cnt + a2.cnt + a3.cnt + a4.cnt = 40
    

提交回复
热议问题