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.
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!