sql插入4和5之间的随机小数+在一个插入查询中从查询中选择

时间:2014-05-23 17:31:30

标签: sql sql-server tsql sql-server-2012

我正在尝试在select table中的表中插入结果+我想在一个插入查询中生成随机值,范围在4到5之间。 这就是我目前所拥有的:

  INSERT INTO a(PropertyID, TestimonialID, Rating)
  SELECT b.PropertyID, b.TestimonialID 
  FROM [b]
  WHERE b.PropertyID NOT IN(SELECT a.PropertyID FROM a), -- Function for generating rating value between 4 and 5 should come here 

知道如何在sql server 2012中做到这一点?在此先感谢Laziale

更新: 我不需要为所有属性生成的值完全相同

3 个答案:

答案 0 :(得分:4)

这就是我解决的问题:

    INSERT INTO a(PropertyID, TestimonialID, Rating)   SELECT b.PropertyID, b.TestimonialID, 
ROUND(RAND(CHECKSUM(NEWID())) * (5-4),5) + 4 as RandomRating    FROM [b] 
WHERE b.PropertyID NOT IN(SELECT a.PropertyID FROM a)

感谢大家的帮助

答案 1 :(得分:1)

以下内容生成随机小数。

insert into a(PropertyID, TestimonialID, Rating)
select 
    b.PropertyID, 
    b.TestimonialID, 
    (4 + RAND( (DATEPART(mm, GETDATE()) * 100000 )
    + (DATEPART(ss, GETDATE()) * 1000 )
    + DATEPART(ms, GETDATE()) )) as RandomRating
 from  
    [b]
 where  
    b.PropertyID not in (select a.PropertyID from a)

@EDIT:所以,我们需要一个随机的不同种子。如果您的PropertyID列是一个整数,那么尝试使用以下内容从select中替换该部分:

 4 + RAND(b.PropertyID) as RandomRating,

我刚刚使用以下查询对此进行了测试,它运行正常:

select 
    a.col, 
    -- random rating
    4 + RAND(a.col) as RandomRating
from  
(
    select 1 as col
    union select 2 as col
    union select 3 as col
    union select 4 as col
    union select 5 as col
    union select 6 as col
) a

答案 2 :(得分:0)

我认为像这样的代码会起作用。

SELECT 4.0 + CAST(RAND() AS DECIMAL(5,2))

--Result may give like this.
--4.62