我有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组 - 结果都是错误的,我无法思考如何解决它。任何帮助都会很棒。
答案 0 :(得分:0)
这不是一个完整的笛卡儿吗?我这样做非常小心,但是:
select
*
from
(select distinct score from <yourtable>) scores
cross join (select distinct grp from <yourtable>) grps
order by grp,score
我无法想象为什么有人会想要这样做,而且我觉得这个解决方案有点脏。
答案 1 :(得分:0)
您只需使用new_grp
&amp; new_score
代替ev_grp
&amp; 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