2014-02-20 169 views
4

我有一个数据库中的表是这样的:SQL Server 2008 R2的子查询分组,总结和计数

CREATE TABLE dbo.evals (
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [agent_id] [int] NOT NULL, 
    [matrix_1] [int], 
    [matrix_2] [int], 
    [matrix_2] [int]) 

的matrix_(X)列的每个人都有的默认值为0。当代理正在经理评估并不要求每个矩阵都要输入。代理商可以每天进行评估。如果输入矩阵,它将有一个介于1和5之间的值。如果不是,则为0.我需要创建一个报告,对每个代理的每个矩阵进行求和和平均。在计算平均值时,我不需要计算0值,所以我需要以某种方式计算矩阵值<> 0的计数。报告不是针对一个代理,而是针对一个报告中的所有代理。我试图通过agent_id与子查询的一般组得到矩阵计数矩阵<> 0,它不起作用。我想结束的是类似于:

select agent_id, sum(matrix_1)/(count(matrix_1) where matrix_1 <> 0), 
      sum(matrix_2)/(count(matrix_2) where matrix_2 <> 0), 
      sum(matrix_3)/(count(matrix_3) where matrix_3 <> 0) 
group by agent_id 

这只是伪代码说明所需的结果。我曾尝试使用子查询中的每个列使用子查询中的分组,但没有奏效。

回答

4

伟大的问题吉姆!这应该做到这一点。如果你想要一个更好的平均水平,投你的价值观作为浮动的Avg聚集:

select 
    agent_id, 
    sum(matrix_1) Matrix1Sum, 
    avg(case when matrix_1 > 0 then cast(matrix_1 as float) end) Matrix1Average, 
    sum(matrix_2) Matrix2Sum, 
    avg(case when matrix_2 > 0 then cast(matrix_2 as float) end) Matrix2Average, 
    sum(matrix_3) Matrix3Sum, 
    avg(case when matrix_3 > 0 then cast(matrix_3 as float) end) Matrix3Average 
from evals 
group by 
    agent_id 
+0

@罗恩·史密斯 - 这正是我需要的 - 完美的作品什么我的要求是 - 谢谢你。 –

+0

非常欢迎您先生! :) –