将所有 SQL 行排列组合在一起,包括高阶排列

Join all SQL row permutations together, including higher-order permutations

我有3行这样的数据:-

Score | Grp
1     | A
10    | B
100   | C

我想要所有组合,就像这样:-

Score | Grp
1     | A
10    | B
100   | C
11    | A/B
101   | A/C
110   | B/C
111   | A/B/C

(以后可能会超过3组。)

在 Teradata 上,这段代码让我明白了很多(rn 是行号,每行的顺序整数):-

with recursive cte(ev_grp, score, rn, new_grp, new_score) as
 ( select l.ev_grp, l.score, l.rn, ev_grp as new_grp, score as new_score 
   from in_tab as l

   union all

   select inn.ev_grp, inn.score, inn.rn, 
          inn.ev_grp||'/'||cte.ev_grp as new_grp, (inn.score + cte.score) as new_score
   from in_tab as inn  
   join cte
   on inn.rn > cte.rn
 )    
select f.*
from cte f 
order by f.new_score

然而,最后一行 - 所有 3 组 - 结果都是错误的,我想不出如何解决它。任何帮助都会很棒。

这不就是一个完整的笛卡尔坐标吗?我会非常小心地这样做,但是:

select
*
from
(select distinct score from <yourtable>) scores
cross join (select distinct grp from <yourtable>) grps
order by grp,score

我无法想象为什么会有人想要这样做,而且我觉得建议这个解决方案有点脏。

您只需要使用 new_grp & new_score 而不是 ev_grp & score。并注意 new_grp 不会被截断:

with recursive cte(ev_grp, score, rn, new_grp, new_score) as
 ( select l.ev_grp, l.score, l.rn, 
      CAST(ev_grp AS VARCHAR(1000)) as new_grp, -- must be large enough to store all concatenated groups 
      score as new_score 
   from in_tab as l

   union all

   select inn.ev_grp, inn.score, inn.rn, 
          inn.ev_grp||'/'||cte.new_grp as new_grp, (inn.score + cte.new_score) as new_score
   from in_tab as inn  
   join cte
   on inn.rn > cte.rn
 )    
select f.*
from cte f 
order by f.new_score