Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting x rows based off a column value

I've had a look about and seen some examples, but none that suit my needs.

I have a table:

+-------+-----------+-----------+
| Year  |   Month   |   Count   |     
+-------+-----------+-----------+
| 2001  |    Nov    |    2      |   
| 2001  |    Dec    |    1      |   
| 2002  |    Jan    |    3      |  
+-------+-----------+-----------+

Now the idea is I want to insert the Year and Month values x times into another table based on the Count Value. So I should end up with something like the following:

+-------+-----------+
| Year  |   Month   |    
+-------+-----------+
| 2001  |    Nov    |   
| 2001  |    Nov    |  
| 2001  |    Dec    |   
| 2002  |    Jan    |   
| 2002  |    Jan    | 
| 2002  |    Jan    |  
+-------+-----------+

This is just a small sample, the actual table is much larger.

Any pointers on this would be great. I hope what I am asking makes sense, any questions, please ask :)

like image 790
JimmyPop13 Avatar asked Sep 11 '25 09:09

JimmyPop13


1 Answers

You can also use a recursive cte as

WITH CTE AS
(
  SELECT *
  FROM T
  UNION ALL
  SELECT [Year], [Month], [Count] -1
  FROM CTE
  WHERE [Count]-1 > 0
)
SELECT T.*
FROM T LEFT JOIN CTE
       ON T.Year = CTE.Year
          AND
          T.Month = CTE.Month
like image 61
Ilyes Avatar answered Sep 12 '25 23:09

Ilyes