如何在sql中将数据转换为这种形式:

bqjvbblv  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(629)

输入:

我必须把数据从输入转换成输出。如果for id freq为n,则创建该id的n行。
输出:

dtcbnfnu

dtcbnfnu1#

在presto中,一个选项使用 sequence() 以及横向连接以生成行:

select t.id, x.value
from mytable t
cross join lateral unnest(sequence(1, t.freq)) as x(value)
order by t.id, x.value
xzabzqsa

xzabzqsa2#

好问题-一种方法是使用整数表-如果您确定重复次数不会超过(比如)128次,您可以按如下方式创建整数表:

CREATE TABLE nums(i INT PRIMARY KEY);
INSERT INTO nums VALUES (1);
INSERT INTO nums SELECT 1+i FROM nums;
INSERT INTO nums SELECT 2+i FROM nums;
INSERT INTO nums SELECT 4+i FROM nums;
INSERT INTO nums SELECT 8+i FROM nums;
INSERT INTO nums SELECT 16+i FROM nums;
INSERT INTO nums SELECT 32+i FROM nums;
INSERT INTO nums SELECT 64+i FROM nums;

现在您可以使用该表:

SELECT id, i AS value
 FROM input JOIN nums ON i BETWEEN 1 AND Freq
zz2j4svz

zz2j4svz3#

我会像gmb显示的那样用侧边。但是,在sql server中,可以通过另一种方式执行,例如:

with tally as 
(
  select top(select max(v) from myTable)
  ROW_NUMBER() OVER (ORDER BY t1.Object_ID) AS N
            FROM Master.sys.All_Columns t1
            CROSS JOIN Master.sys.All_Columns t2
)
select m.id, t.N
from tally t
cross join myTable m 
where t.N <= m.v
order by m.id, t.N;

dbfiddle演示

相关问题