计数除以计数

时间:2014-04-04 21:38:06

标签: tsql count sum

如何将计数除以另一个计数。我见过几种不同的方法,但我无法让它们为我的目的而工作。我目前正在处理的代码是:

Select(select COUNT(lUsers) 
        FROM Tlocation
        WHERE dLastUpdated IS NOT NULL 
            AND dRemovalDate BETWEEN DATEADD(day,-7,GETDATE()) and GETDATE())
                /
            (SELECT COUNT(lUsers) 
        FROM Tlocation 
        WHERE dLastUpdated < GETDATE() 
            AND dRemovalDate IS NULL OR dRemovalDate > GETDATE())

但每次只返回0。

1 个答案:

答案 0 :(得分:0)

因为该值小于INT(COUNT()返回)。以下是如何做到的:

SELECT
    (
        SELECT 1562 
    )
    /
    CAST(
        (
            SELECT 92825
        )
        AS DECIMAL(20, 10)
    )
;

或者您的查询:

Select(select COUNT(lUsers) 
        FROM Tlocation
        WHERE dLastUpdated IS NOT NULL 
            AND dRemovalDate BETWEEN DATEADD(day,-7,GETDATE()) and GETDATE())
                /
            CAST(
                    (SELECT COUNT(lUsers) 
                FROM Tlocation 
                WHERE dLastUpdated < GETDATE() 
                    AND dRemovalDate IS NULL OR dRemovalDate > GETDATE())
            AS DECIMAL(20, 10)
            )
;