SQL Server – Select Repeating Number X Times and Then Increment

querysql serversql-server-2008

I need a select query that can generate z amount of rows starting from 1, repeating x times and then increment to the next number.

For example 10 rows repeating 4 times would result in the following:

| # |  
|---|  
| 1 |  
| 1 |  
| 1 |  
| 1 |  
| 2 |  
| 2 |  
| 2 |  
| 2 |  
| 3 |  
| 3 |

Best Answer

DECLARE @z INT=10, @x INT=4;
WITH q AS (SELECT 0 AS n UNION ALL SELECT n+1 FROM q)
SELECT TOP(@z) n/@x+1 FROM q OPTION(MAXRECURSION 0);