【问题标题】:How to duplicate table row based on column value in Teradata?如何根据 Teradata 中的列值复制表行?
【发布时间】:2021-08-26 23:34:11
【问题描述】:
有人可以帮助完成这项任务吗?如果我在 Teradata 中有一个如下表:
| caseid |
content |
repeat |
| id1 |
row1 |
2 |
| id2 |
row2 |
3 |
我想根据重复值构建一个新表,如下所示。我该怎么办?
| caseid |
content |
repeat |
groupid |
| id1 |
row1 |
2 |
1 |
| id1 |
row1 |
2 |
2 |
| id2 |
row2 |
3 |
1 |
| id2 |
row2 |
3 |
2 |
| id2 |
row2 |
3 |
3 |
谢谢!
【问题讨论】:
标签:
sql
teradata
teradata-sql-assistant
teradatasql
【解决方案1】:
Teradata 专有的 EXPAND ON 语法创建时间序列并可用于此任务:
SELECT t.*
-- convert period back to int
,End(pd) - Current_Date AS groupid
FROM mytable AS t
-- works on date/time only -> convert int to period
EXPAND ON PERIOD(Current_Date, Current_Date + repeat) AS pd
【解决方案2】:
您可以使用递归 cte 来做到这一点:
with recursive cte as (
select * , 1 groupid from cases
union all
select caseid ,content, repeat, groupid + 1 groupid
from cte
where groupid < repeat
)
select * from cte
order by caseid
酪蛋白 |内容 |重复 |群号
-----: | :-------- | -----: | ------:
1 |第 1 行 | 2 | 1
1 |第 1 行 | 2 | 2
2 |第 2 行 | 3 | 1
2 |第 2 行 | 3 | 2
2 |第 2 行 | 3 | 3
db小提琴here