1

我有一个以字符串形式获取 sql 查询的过程。例子:

SELECT SUM(Refuse) FROM FOOD_DES WHERE Refuse > 1

但我只需要对满足条件的行求和。条件如下:

CONVERT(INT,RAND() * 100 ) <= @probability

但这不起作用(它总结了所有元素):

SELECT SUM(Refuse) FROM FOOD_DES WHERE Refuse > 1 AND
CONVERT(INT,RAND() * 100 ) <= @probability

所以接下来尝试:

SELECT SUM(Refuse) FROM FOOD_DES  AS T CROSS APPLY fn_probability() AS F

CREATE FUNCTION fn_probability ( )
RETURNS @probabilityInfo TABLE ( Result INT )
AS 
    BEGIN 
        DECLARE @rand INT
        SET @rand = ( SELECT TOP 1
                                RandValue
                      FROM      RandView
                    )
        IF @rand <= 80 
            INSERT  INTO @probabilityInfo
                    ( Result )
            VALUES  ( 1 )
        RETURN  
    END
CREATE VIEW RandView
AS 
SELECT CONVERT(INT, RAND() * 100) AS RandValue

但它也不起作用。任何的想法?:)

4

2 回答 2

1

像这样怎么样:

WITH data(Refuse, RandomNumber) AS
(
    SELECT 
        Refuse
        ,CONVERT(INT, RAND(CHECKSUM(NEWID())) * 100) 
    FROM 
        FOOD_DES
    WHERE 
        Refuse > 1
)
SELECT
    SUM(Refuse) 
FROM
    data
WHERE
    RandomNumber <= @probability
于 2012-05-04T21:08:21.930 回答
1

rand()本身不起作用,因为它只在语句期间执行一次。

当我需要一组随机的行时,我通常会选择一个伪随机数:

select sum(refuse)
from 
(
   SELECT Refuse,
      row_number()  over (partition by null order by (select '')) as rownum
   FROM FOOD_DES
   WHERE Refuse > 1
) t
where mod(rownum*101-67, 100) < @probability
于 2012-05-05T03:22:44.663 回答