在SQL Server中为每行的0.85和0.95生成随机数
我想为每行的0.85和0.95生成一个随机数。
首先,我尝试使用(rand()*(0.85-0.95)+0.95),但每行都生成相同的数字。
我的查询看起来像这样:
select
case when x=1 then (rand()*(0.85-0.95)+0.95) else 0
from abcd
I'd like to generate a random number between 0.85 and 0.95 for each row.
At first I tried using (rand()*(0.85-0.95)+0.95) but the same number was generated for every single row.
My query looks like something like this:
select
case when x=1 then (rand()*(0.85-0.95)+0.95) else 0
from abcd
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
rand()
返回给定语句的相同数字。解决方案是使用newid()
。类似:转换(十进制(2,2),.85 +(.95 - .85)*rand(checksum(newid())))
fiddle 在这里
RAND()
returns the same number for a given statement. A solution would be to useNEWID()
. Something like:CONVERT( DECIMAL(2, 2), .85 + (.95 - .85 )*RAND(CHECKSUM(NEWID())))
Fiddle here
也许使用newid生成随机数;因为兰德()将为表中的所有行提供相同的值,因为种子不会改变。我们可以使用NewID来馈入每行新的种子值并获得差异随机数。
因此,您的情况状况更像
;fiddle = 2f37128d33ff1234017b108aA108A10DA7E37
Maybe use NEWID for generating random numbers; as RAND() will give same values for all rows in the table as seed does not change. We can use NEWID to feed new seed values per row and get a diff random number.
so your case condition is more like
fiddle
and your query like