I have a table that looks like this
+-------+------+------+----------+
| Index | F1 | F2 | Multiply |
+-------+------+------+----------+
| 0 | LG | SC | 1 |
| 1 | WE | CC | 1 |
| 2 | TY | PL | 2 |
+-------+------+------+----------+
And I want to multiply the 'Multiply' Column by 2 to determine how many rows to add to the result. With the example above, I want my SQL Query to return:
+------+-----+-----+
|Index | F1 | F2 |
+------+-----+-----+
| 0 | LG | SC |
| 0 | LG | SC |
| 1 | WE | CC |
| 1 | WE | CC |
| 2 | TY | PL |
| 2 | TY | PL |
| 2 | TY | PL |
| 2 | TY | PL |
+------+-----+-----+
I don't have much experience writing SQL queries so help would be much appreciated.
Try this
Edit: adding some description
By writing a query like
we can double rows in the table. And
cross join (values (1),(2),(3),(4)) t(n)
will quadruple the rows. In this case row multiplication will depend on columnMultiply
. So we need to multiply by 2 value of columnMultiply
and join with table with sequence of numbers (0,1,2,3,4,5,6,7...) where number is less than calculated value. For example, forMultiply = 2
, join condition will be 4 numbers (0, 1, 2, 3) which are less than 2*2. And those 4 numbers will quadruple initial row.master.dbo.spt_values
is only used to get numbers sequence. Sequence can be generated at runtime or another table with numbers sequence can be usedAnother way is to use recursive CTE:
Output: