SQL返回百分比

时间:2011-07-14 13:32:35

标签: sql sql-server sql-server-2008

尝试创建一个查询,将向我发回USER_TOT_REQS的百分比。

如何以小数形式返回结果?

SELECT  u.USER_NAME
    ,SUM(t.REQ_AMOUNT) as 'USER_TOTAL_AMOUNT'
    ,COUNT(t.ID) as 'USER_TOT_REQS'
    ,(COUNT(t.ID)* 100 / (Select COUNT(*) from TB__TOMBSTONES t 
    JOIN TB__USERS u 
    ON u.ID = t.CURRENT_BUYER__ID
        WHERE 1=1
        AND t.REGION__ID = 1
        AND t.OFFICE__ID = 1
        AND t.STL_ASSIGNED__ID = 8)) AS 'Percentage'
FROM TB__TOMBSTONES t 
    JOIN TB__USERS u 
    ON u.ID = t.CURRENT_BUYER__ID
WHERE 1=1
AND t.REGION__ID = 1
AND t.STL_ASSIGNED__ID = 8
GROUP BY u.USER_NAME
ORDER BY USER_TOTAL_AMOUNT DESC

基于我在stackoverflow上看到的几个例子 - 谢谢。

4 个答案:

答案 0 :(得分:5)

要获取小数值,请将100更改为100.0,否则所有内容都会被隐式视为INT。

答案 1 :(得分:3)

您的计数被反转。外部选择的选择性低于嵌套选择(它有一个额外的t.OFFICE__ID = 1谓词...(除非你忘记在外部选择中?)

表达式应为

(SELECT COUNT(*) ...[nested select]) * 100.0 / COUNT(t.ID) AS Percentage

为了提高精度,请设置100.0,但这可能不是主要问题...除此之外,嵌套选择不会加入外部选择的用户。相反,对于每个组,它会选择所有用户。所以更正确:

(SELECT COUNT(*) from TB__TOMBSTONES t2
    -- self-join t2 to the outer user. No need to join user again
    WHERE t2.CURRENT_BUYER__ID = t.CURRENT_BUYER__ID
    AND t2.REGION__ID = 1
    AND t2.OFFICE__ID = 1
    AND t2.STL_ASSIGNED__ID = 8) * 100.0 / COUNT(t.ID) AS Percentage

答案 2 :(得分:1)

也许尝试CAST或CONVERT - 将你的红利和除数改为DECIMAL类型。

CAST( (COUNT(t.ID)*100) AS DECIMAL )

CAST( (COUNT(*) AS DECIMAL )

问题是你用整数计算:

“如果整数被除数除以整数除数,则结果是一个整数,其截断结果的任何小数部分。”

http://msdn.microsoft.com/en-us/library/ms175009.aspx

答案 3 :(得分:0)

如果您的任何输入是int,请尝试以下

转换(Float,(int_value1 - int_value2)/ int_value2)* 100