仅汇总满足概率条件的行

时间:2012-05-04 21:03:51

标签: sql tsql

我有一个在字符串中获取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

但它既不起作用也不起作用。 有什么想法吗?:)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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