sql count和sum在同一个语句中

时间:2014-05-24 01:39:55

标签: sql oracle count group-by sum

如何执行以下操作,我基本上需要计算应用程序的总数,然后将其除以另一列的总和。

这是我的查询,

 select TIME_ID, CAMPUSID, GenderId, FEETYPEID, PrefRankId, QUALIFID, PRIMARYSTUDYFIELD, SUPSTUDYFIELD,IsYear12Id, COURSEID
        , count(APPID) as TOT_NUM_APP, sum(ATAR) as TOT_ATAR, round(SUM(ATAR)/(SUM(COUNT(APPID)) OVER () ) AS TOT_ATAR_AVG
      from temp_fact tf1
      group by TIME_ID, CAMPUSID, GenderId, FEETYPEID, PrefRankId, QUALIFID, 
                PRIMARYSTUDYFIELD, SUPSTUDYFIELD,IsYear12Id,courseid;

参见上面的查询。但这是错误的,因为我想要ATAR的平均值是TOT_NUM_APP / TOT_ATAR

enter image description here

1 个答案:

答案 0 :(得分:0)

大多数数据库都支持窗口功能。因此,如果我理解正确,sum(count(appid))应该代表所有行的总计数。如果是这样的话:

SELECT TIME_ID, CAMPUSID, GenderId, FEETYPEID, PrefRankId, QUALIFID, PRIMARYSTUDYFIELD,
       SUPSTUDYFIELD, IsYear12Id, courseid , count(APPID) as TOT_NUM_APP,
       SUM(ATAR)/(SUM(COUNT(APPID)) OVER ()) as TOT_STUD_ATAR
FROM temp_fact tf1
GROUP BY TIME_ID, CAMPUSID, GenderId, FEETYPEID, PrefRankId, QUALIFID, PRIMARYSTUDYFIELD,
         SUPSTUDYFIELD, IsYear12Id, courseid;