如何获得列值不等于零的平均值?

时间:2014-06-17 23:24:18

标签: sql sql-server-2008

我有一个查询

Select AVG(((cast(c.rating1 as Float)+ cast(c.rating2 as Float)+cast (c.rating3 as Float)+cast(c.rating4 as Float)+cast(c.rating5 as Float))/5))
From CSEReduxResponses c
Where 
     c.execoffice_date BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @today)-1, 0)
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, @today)-1, -1)
AND c.execoffice_status =1
AND C.rating1 <> 0 AND C.rating2 <> 0 AND C.rating3 <> 0 AND C.rating4 <> 0 AND 
C.rating5 <> 0

我获得1-5评级的平均值,但我也计算等于&#39; 0&#39;的等级。

我怎样才能只计算评级[x]不等于&#39; 0&#39; ? 它仍然会计数,但除了将其除以5之外,它将除以多少列不是&#39; 0&#39;。

我创建了一个&lt; http://sqlfiddle.com/#!3/570fa/7&gt;

2 个答案:

答案 0 :(得分:2)

不太漂亮但应该有效:

  SELECT AVG((... SUM of 5 ratings ...) /
           (CASE WHEN rating1 > 0 THEN 1 ELSE 0 END + 
            CASE WHEN rating2 > 0 THEN 1 ELSE 0 END +
            CASE WHEN rating3 > 0 THEN 1 ELSE 0 END +
            CASE WHEN rating4 > 0 THEN 1 ELSE 0 END +
            CASE WHEN rating5 > 0 THEN 1 ELSE 0 END))
  FROM ...
  WHERE ...

做完这样的事情之后,应该感谢数据规范化。

答案 1 :(得分:1)

尝试使用VALUES获取每行的非0值的平均值。

SELECT
(
    SELECT AVG(rating)
    FROM (VALUES 
        (cast(c.rating1 as Float)), 
        (cast(c.rating2 as Float)), 
        (cast(c.rating3 as Float)), 
        (cast(c.rating4 as Float)), 
        (cast(c.rating5 as Float))
    ) AS v(rating)
    WHERE v.rating <> 0
) avg_rating
From CSEReduxResponses c
Where 
     c.execoffice_date BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @today)-1, 0)
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, @today)-1, -1)
AND c.execoffice_status = 1

http://sqlfiddle.com/#!3/570fa/26

我从WHERE

中删除了以下条件
AND C.rating1 <> 0 AND C.rating2 <> 0 AND C.rating3 <> 0 AND C.rating4 <> 0 AND 
C.rating5 <> 0

因为如果你留下它,你只计算有5个非0评级的行的平均值,我猜这不是你的意图。

要获得所有行中非0评级的平均值,请将所有非0评级的总和除以非0评级的总计数。

SELECT
    CAST(SUM(sum_rating) as float)/SUM(count_rating)
From CSEReduxResponses c
CROSS APPLY (
    SELECT SUM(rating), COUNT(rating)
    FROM (VALUES 
        (c.rating1), 
        (c.rating2), 
        (c.rating3), 
        (c.rating4), 
        (c.rating5)
    ) AS v(rating)
    WHERE v.rating <> 0
) AS x (sum_rating, count_rating)
Where 
    c.execoffice_date BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
AND c.execoffice_status = 1

http://sqlfiddle.com/#!3/570fa/35

正如其他人所说,如果可能,你应该考虑规范你的表格。