You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Oracle SQL Developer中根据列值生成多行重复数据?

按指定次数重复列数据的实现方案

你的需求完全可以实现,以下是几种常用工具的具体实现方法:

原始数据

Column AColumn B
John2
Benedic3

目标结果

Column A
John
John
Benedic
Benedic
Benedic

1. Excel/Google Sheets 实现

支持动态数组的版本(Excel 365/Google Sheets)

在空白单元格输入以下公式,自动生成结果:

=TOROW(TEXTSPLIT(TEXTJOIN(",",TRUE,REPT(A:A&",",B:B)),","),,TRUE)

旧版Excel(无动态数组支持)

可以用VBA宏批量处理:

Sub RepeatRows()
    Dim ws As Worksheet
    Dim lastRow As Long, i As Long, j As Long
    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    For i = lastRow To 2 Step -1
        For j = 1 To ws.Cells(i, "B").Value - 1
            ws.Rows(i).Copy
            ws.Rows(i + 1).Insert Shift:=xlDown
        Next j
    Next i
    ws.Columns("B").Delete
End Sub

运行宏后即可得到目标结果。

2. Python(Pandas)实现

通过Pandas的repeat方法快速完成:

import pandas as pd

# 构造原始数据
df = pd.DataFrame({
    'Column A': ['John', 'Benedic'],
    'Column B': [2, 3]
})

# 按指定次数重复行并提取目标列
result_df = df.loc[df.index.repeat(df['Column B'])][['Column A']].reset_index(drop=True)

print(result_df)

3. SQL 实现

使用递归CTE生成重复数据(以PostgreSQL为例,其他数据库语法可按需调整):

WITH RECURSIVE repeat_cte AS (
    SELECT "Column A", "Column B", 1 AS current_count
    FROM your_table
    UNION ALL
    SELECT "Column A", "Column B", current_count + 1
    FROM repeat_cte
    WHERE current_count < "Column B"
)
SELECT "Column A" FROM repeat_cte ORDER BY "Column A";

内容的提问来源于stack exchange,提问作者Yudha Patria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:52:17