试图获得计数结果集的平均值

时间:2011-10-12 09:23:46

标签: sql count db2 resultset average

我有以下SQL :( bitemp)

SELECT COUNT (*) AS Count
  FROM Table T
 WHERE (T.Update_time =
           (SELECT MAX (B.Update_time )
              FROM Table B
             WHERE (B.Id = T.Id))
GROUP BY T.Grouping

现在我得到的结果集有很多数字。我想得到这份清单的平均值。目前,我将列表导入excel并使用其平均功能。但是DB2有一个AVG函数,但我没有让它工作。

我尝试了SELECT AVG(COUNT(*))SELECT AVG(*) FROM (theQuery)

1 个答案:

答案 0 :(得分:47)

您可以将查询作为子查询:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

编辑:我认为这应该是一样的:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))