3

Input:

Input

I have to Convert data from input to output. where we trying if for id freq is n then create n rows of that id.

Output:

output

GMB
  • 216,147
  • 25
  • 84
  • 135

3 Answers3

2

In Presto, one option uses sequence() and a lateral join to generate the rows:

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
Piotr Findeisen
  • 19,480
  • 2
  • 52
  • 82
GMB
  • 216,147
  • 25
  • 84
  • 135
1

Great question - one approach is to use a table of integers - if you are certain there will never be more than (say) 128 repeats you can create the table of integers as follows:

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;

Now you can use that table:

SELECT id, i AS value
 FROM input JOIN nums ON i BETWEEN 1 AND Freq
SQL Hacks
  • 1,322
  • 1
  • 10
  • 15
1

I would do that with Lateral as GMB showed. In SQL server however it could be done in another way like below as an example:

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 demo

Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39