SQL Server 2012查询计算计算

时间:2013-11-21 19:00:33

标签: math sql-server-2012

我正在SQL Server中构建一个查询,用于计算我们为调查收到的分数。我们有一个名为overall_score的列,其中用户输入1-5中的数字作为评级。我正在尝试创建一个存储过程,根据分数计算评级。

Score rating = (Total count of scores 4 and 5)/(Total number of responses) * 100

我有三个单独的select语句可以创建我需要的结果,但当我将它们组合在一起时,我的输出为0.

有人可以指导我在这里做错了吗?

单独的SQL语句:

SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 4;  
SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 5;  
SELECT count(overall_score) FROM Layer1_DataMerge;  

结合在一起:

SELECT distinct
(  
    (
        (SELECT count(overall_score) FROM Layer1_DataMerge WHERE Overall_Score = 4) +  
        (SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 5)
    ) / (SELECT count(overall_score) FROM Layer1_DataMerge)
) AS CSAT  
FROM Layer1_DataMerge;

1 个答案:

答案 0 :(得分:2)

原因你得到零是因为你正在做整数除法。使用整数除法1/3 = 0.您需要转换为浮点运算,而且您可以在一个查询中完成所有操作:

SELECT 100.0 * 
       (SUM(CASE WHEN overall_score = 4 THEN 1 ELSE 0 END) + 
       SUM(CASE WHEN overall_score = 5 THEN 1 ELSE 0 END)) / 
       COUNT(overall_score)

SELECT 100.0 * 
       SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END) / 
       COUNT(overall_score)

要仅显示2位小数,您可以强制转换为包含2位小数的数字类型:

SELECT CAST(
         100.0 * 
         SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END) / 
         COUNT(overall_score)
       AS NUMERIC(5,2))

或使用STR转换为字符串:

SELECT STR(
         100.0 * 
         SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END) / 
         COUNT(overall_score)
       ,5,2)