Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite - Repeat rows based on column values

Tags:

sqlite

Here is how dataset looks like

Key1  Start  End
 A     5      8
 B     2      4

I am looking for output as shown below where a new column "Num" is created and it should start with respective row value of "Start" and increment by +1 and stop at "End" number. The final result should be able to save in a new table.

Key1 Num Start End
A     5   5     8
A     6   5     8
A     7   5     8
A     8   5     8
B     2   2     4
B     3   2     4
B     4   2     4

I could find some solutions in Sqlserver but not in SQLite.

like image 393
HKE Avatar asked May 24 '26 16:05

HKE


2 Answers

You can do it with recursive CTE:

with cte as (
  select Key1, Start Num, Start, End
  from tablename
  union all
  select Key1, Num + 1, Start, End
  from cte 
  where Num < End
)  
select * from cte
order by Key1, Start, End, Num

See the demo.
Results:

| Key1 | Num | Start | End |
| ---- | --- | ----- | --- |
| A    | 5   | 5     | 8   |
| A    | 6   | 5     | 8   |
| A    | 7   | 5     | 8   |
| A    | 8   | 5     | 8   |
| B    | 2   | 2     | 4   |
| B    | 3   | 2     | 4   |
| B    | 4   | 2     | 4   |
like image 55
forpas Avatar answered May 28 '26 09:05

forpas


I have no experience in SQLlite but feel below should help you:

SELECT key1, (Select value from generate_series(start, end,1)) as Num, Start, End from table;

You need to get generate_series extension installed for this.

like image 28
Krishna Kishore Avatar answered May 28 '26 07:05

Krishna Kishore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!