Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate rows in SELECT statement

Tags:

sql

sql-server

I'm trying my best to avoid using cursors- the amount of data is really huge. There is a table that looks like:

|Data| Multiplier|
-----------------|
|A   | 2         |
|B   | 3         |
|C   | 0         |

I need to get data from it in the following way:

|Data| Multiplier|
-----------------|
|A   | 2         |
|A   | 2         |
|B   | 3         |
|B   | 3         |
|B   | 3         |

So that the row appears as much times, as it's "Multiplier" value. I know it's possible to use CONNECT statements in Oracle Database, but I need to do it in MSSQL.

like image 250
Hirasawa Yui Avatar asked Dec 18 '22 22:12

Hirasawa Yui


1 Answers

You need recursive way :

with t as (
     select data, Multiplier, 1 as seq
     from table
     where Multiplier > 0
     union all
     select data, Multiplier, seq+1
     from t
     where seq < Multiplier
)
select *
from t
option (maxrecursion 0);
like image 122
Yogesh Sharma Avatar answered Jan 01 '23 20:01

Yogesh Sharma