Question

Using the RAND() function or NEWID() to generate a random value in each column as described here you can generate random values in a row. But... the value repeats the same in every row.

enter image description here

How can you generate a random value in each row for every column? I would like to show in column B1 a random product which is also in group '102'. The same for column B2 but a different product. And the next row again two different products and so on. The result will show 2 alternative products from the same group per product (row).

My code looks something like this:

DECLARE @B1 varchar(30)
DECLARE @B2 varchar(30)
SET @B1 = (SELECT TOP 1 ItemCode FROM items WHERE items.Assortment IN (102) ORDER  BY RAND())
SET @B2 = (SELECT TOP 1 ItemCode FROM items WHERE items.Assortment IN (102) ORDER  BY NEWID())

SELECT ProdCode, ProdName, @B1 as B1, @B2 as B2
FROM Products
WHERE ProductGroup IN (102) --use IN so you can select multiple groups

Thanks!

Was it helpful?

Solution

You need to add something from the main query so the subquery gets recalculated for each row - ie:

SELECT 
    ProdCode, 
    ProdName, 
    (
        SELECT TOP 1 ItemCode 
        FROM items 
        WHERE items.Assortment IN (102) AND itemcode <> products.ProdCode
        ORDER BY NEWID(), products.ProdCode
    )
FROM Products
WHERE ProductGroup IN (102) 

OTHER TIPS

Here is a way that would work by using a while loop to loop through the rows in your table:

If you have an ID Column or something on the Products Table or insert it into a temp table to handle the calculation the below method will help.

    DECLARE @MaxRowID INT
    DECLARE @RowID INT
    DECLARE @RandomNum FLOAT

    SET @RowID = 1

    SELECT @MaxRowID = MAX(ID) FROM Products

    WHILE ( @RowID <= @MaxRowID )
        BEGIN

            SET @RandomNum = RAND()

            UPDATE Products
            SET RandomNum = @RandomNum
            WHERE ID = @RowID

            SET @RowID = @RowID + 1

        END

    SELECT * FROM #Test

    DROP TABLE #Test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top