简体   繁体   English

每行从表中选择的TSQL随机值

[英]TSQL random value from table select in every row

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. 使用RAND()函数或NEWID()以生成作为每一列的随机值这里描述可以生成连续的随机值。 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'. 我想在B1栏中显示一个随机产品,该产品也在“ 102”组中。 The same for column B2 but a different product. B2列相同,但产品不同。 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). 结果将显示每个产品(行)来自同一组的2个替代产品。

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

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) 

Here is a way that would work by using a while loop to loop through the rows in your table: 这是一种通过使用while循环遍历表中的行的方法:

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. 如果您在产品表上有一个ID列或其他内容,或将其插入到临时表中以处理计算,则以下方法将有所帮助。

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM