Question

I have a column in a table, and I want to divide it's rows into four equal groups (or columns, whichever is easier to implement) with random allocation.

Suppose the rows of column look like:

**id**
1
2
3
4
5
6
7
8
9
10
11
12

I would like the output to be like:

*id_A  id_B  id_C  id_D*
 3     8     5     1
 6     2     4     12
 11    9     7     10

One possible way of doing it is displaying the rows in random order using newid() and then selecting every 5th record alternatively for each group. Is there any other simpler way to achieve the desired outcome?

Was it helpful?

Solution

You can use ranking functions and slice the inner results into quarters and then partition again for a final pivot on quarter. The quarters are not random but evenly distributed. In a table with 100 rows Row 1,25,50 and 100 would go into column1. However, using a guid and some ordering in the two inner queries would yield randomness.

SELECT 
    [1] AS COL_1,[2] AS COL_2,[3] AS COL_3,[4] AS COL_4 
FROM
(
    SELECT  
        TableID,
        RowNumber=ROW_NUMBER() OVER (PARTITION BY QuartTile ORDER BY QuartTile),
        QuartTile
    FROM
    (
        SELECT
            TableID,
            QuartTile=NTILE(4) OVER(ORDER BY NEWID())

        FROM
            Table
    )AS Z
)X
PIVOT (AVG(TableID) FOR QuartTile IN([1],[2],[3],[4]) )AS PVT
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top