多行的不同 rand() 值 SQL 服务器
Different rand() value for multiple rows SQL Server
当我使用这个查询时,它为每一行分配相同的值。
有什么办法可以避免这种情况发生吗?
UPDATE Team
SET GroupID = CAST(RAND() * 4 AS INT)
澄清一下:
这将与 Netbeans 一起使用,为团队分配组号。
+----+----------+-------------+------------------+---------+
| ID | School | TeamCaptain | Email | GroupID |
+----+----------+-------------+------------------+---------+
| 1 | School 1 | John | email@email.com | NULL |
| 2 | School 2 | James | email2@email.com | NULL |
+----+----------+-------------+------------------+---------+
SandySands 方法有效。但是,有什么办法可以让同一个数字出现的次数不超过4次呢?
试试这个,它对我有用。
UPDATE Team
SET GroupID = CAST(RAND(CHECKSUM(NEWID()))*10000000 AS INT)
WHERE GroupID IN (SELECT GroupID FROM Team
GROUP BY GroupID
HAVING COUNT(GroupID)<4)
此代码确保为团队 table 中的所有 GroupId 分配随机值,并且任何 GroupID 都不会出现超过 4 个
一种方法是:
SELECT *, ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber
FROM TEAM
在更新中使用:
UPDATE Team
SET GroupID = ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber
解决方案取自:
SQL SERVER – Random Number Generator Script – SQL Query
Note: The distribution is pretty good however there are the occasional peaks.
当我使用这个查询时,它为每一行分配相同的值。 有什么办法可以避免这种情况发生吗?
UPDATE Team
SET GroupID = CAST(RAND() * 4 AS INT)
澄清一下: 这将与 Netbeans 一起使用,为团队分配组号。
+----+----------+-------------+------------------+---------+
| ID | School | TeamCaptain | Email | GroupID |
+----+----------+-------------+------------------+---------+
| 1 | School 1 | John | email@email.com | NULL |
| 2 | School 2 | James | email2@email.com | NULL |
+----+----------+-------------+------------------+---------+
SandySands 方法有效。但是,有什么办法可以让同一个数字出现的次数不超过4次呢?
试试这个,它对我有用。
UPDATE Team
SET GroupID = CAST(RAND(CHECKSUM(NEWID()))*10000000 AS INT)
WHERE GroupID IN (SELECT GroupID FROM Team
GROUP BY GroupID
HAVING COUNT(GroupID)<4)
此代码确保为团队 table 中的所有 GroupId 分配随机值,并且任何 GroupID 都不会出现超过 4 个
一种方法是:
SELECT *, ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber
FROM TEAM
在更新中使用:
UPDATE Team
SET GroupID = ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber
解决方案取自:
SQL SERVER – Random Number Generator Script – SQL Query
Note: The distribution is pretty good however there are the occasional peaks.