Oracle分组函数实例

时间:2021-11-20 09:40:34

  分组函数也叫聚合函数。如果在查询只想要查分组函数,那么跟平时的查询语句并无不同:

SQL> SELECT sum(t.PRIZENUM),avg(t.PRIZENUM) FROM T_WLF_AWARDS_RECORD t WHERE t.PRIZETYPE=3 AND t.ISSEND IN (0,1,2,3,10) AND t.ACTIVITYID=4001;
 
SUM(T.PRIZENUM) AVG(T.PRIZENUM)
--------------- ---------------
          40948 4549.7777777777

  但往往不会这么简单,我们会一次查询多个列,包括普通的、没有调用分组函数的列,那么我们要注意以下几点:

  1、所有未包含在组函数中的列都应该包含在 GROUP BY 子句中;

  2、包含在 GROUP BY 子句中的列不必包含在SELECT 列表中;

  3、where条件语句放在GROUP BY子句前面;

SQL> SELECT t2.INVITERMSISDN,t2.INVITEEMSISDN,sum(t2.PRIZENUM),t2.ACTIVETIME
  2          FROM T_WLF_AWARDS_RECORD t2
  3          WHERE t2.PRIZETYPE=3 AND t2.ISSEND IN (0,1,2,3,10)
  4          AND t2.ACTIVITYID=4001
  5          AND t2.ACTIVETIME <=to_date('2018-10-31 00:00:00','yyyy-mm-dd,hh24:mi:ss')
  6          AND to_date('2018-9-01 00:00:00','yyyy-mm-dd,hh24:mi:ss') <=t2.ACTIVETIME
  7          and t2.REWARDTYPE = 0
  8          AND t2.INVITERMSISDN='17682318557'
  9          group by t2.INVITERMSISDN,t2.INVITEEMSISDN,t2.ACTIVETIME,t2.activityid;
 
INVITERMSISDN INVITEEMSISDN SUM(T2.PRIZENUM) ACTIVETIME
------------- ------------- ---------------- -----------
17682318557   40000613773              10086 2018/10/2 1

  4、分组函数可以用在having子句和order by子句中;

SQL> SELECT t2.INVITERMSISDN,avg(t2.PRIZENUM),t2.activityid
  2          FROM T_WLF_AWARDS_RECORD t2
  3          WHERE t2.PRIZETYPE=3 AND t2.ISSEND IN (0,1,2,3,10)
  4          AND t2.ACTIVETIME <=to_date('2018-10-31 00:00:00','yyyy-mm-dd,hh24:mi:ss')
  5          AND to_date('2018-9-01 00:00:00','yyyy-mm-dd,hh24:mi:ss') <=t2.ACTIVETIME
  6          and t2.REWARDTYPE = 0
  7          group by t2.INVITERMSISDN,t2.activityid
  8          having avg(t2.PRIZENUM) > 200
  9          order by avg(t2.PRIZENUM);
 
INVITERMSISDN AVG(T2.PRIZENUM) ACTIVITYID
------------- ---------------- -----------
40000748105                300 6062
40000753029                300 6062
40000753874                300 6062
40000753990                300 6062
40000753949                300 6062
40000756034                300 6062
17682318557              10086 4001
 
7 rows selected

  注意where先筛选出数据,再进行分组函数运算,最后再通过having对结果过滤。