当我使用此查询时,它会将每一行分配给相同的值。 反正有没有让这件事发生?
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次?
答案 0 :(得分:0)
试试这个,它为我工作。
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)
此代码确保为Team表中的所有GroupId分配随机值,并且GroupID的出现次数不会超过4
答案 1 :(得分:0)
一种方法是:
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
注意:分布非常好,但偶尔会出现峰值。