Oracle - 如何在having子句或where子句中使用avg(count(*))?

时间:2017-12-30 12:34:40

标签: sql oracle oracle11g aggregate-functions

我有这样的数据:

CONCERT_ID   EVENT_ID ATTENDANCE AVG_ATTENDANCE_EACH_CONCERT
---------- ---------- ---------- ---------------------------
         1          1          1                         1,5
         1          2          2                         1,5
         3          5          2                           2
         3          6          2                           2
         5         11          4                           2
         5         12          1                           2
         5         13          1                           2

来自此查询:

select concert_id, event_id, count(customer_id) attendance,
avg(count(*)) over (partition by concert_id) avg_attendance_each_concert
from booking
group by concert_id, event_id
order by event_id;

如何限制该查询。我想做的是

如果出勤率低于平均出勤率显示结果

我已经尝试了avg(count(*))over(由concert_id分区)到有条款但是给了我一个错误组功能太深

2 个答案:

答案 0 :(得分:2)

通过仅应用一个嵌套很容易获得所需的结果:

select * from
(
 select concert_id, event_id, count(customer_id) attendance, 
        avg(count(*)) over (partition by concert_id) avg_attendance_each_concert
   from booking
  group by concert_id, event_id
  order by event_id
)
where attendance < avg_attendance_each_concert

D e M o

答案 1 :(得分:1)

加入&#34;中间体&#34; table,一个在上一个问题中返回正确结果的查询。然后从中选择值 - 满足新条件。

SQL> with booking (concert_id, event_id, customer_id) as
  2  (select 1, 1, 10 from dual union
  3   select 1, 2, 10 from dual union
  4   select 1, 2, 20 from dual union
  5   --
  6   select 3, 5, 10 from dual union
  7   select 3, 5, 20 from dual union
  8   select 3, 6, 30 from dual union
  9   select 3, 6, 40 from dual union
 10   --
 11   select 5, 11, 10 from dual union
 12   select 5, 11, 20 from dual union
 13   select 5, 11, 30 from dual union
 14   select 5, 11, 40 from dual union
 15   select 5, 12, 50 from dual union
 16   select 5, 13, 60 from dual
 17  ),
 18  inter as
 19  (select concert_id, event_id, count(customer_id) attendance,
 20          avg(count(*)) over (partition by concert_id) avg_attendance_each_concert
 21   from booking
 22   group by concert_id, event_id
 23  )
 24  select concert_id, event_id, attendance, avg_attendance_each_concert
 25  from inter
 26  where attendance < avg_attendance_Each_concert
 27  order by event_id;

CONCERT_ID   EVENT_ID ATTENDANCE AVG_ATTENDANCE_EACH_CONCERT
---------- ---------- ---------- ---------------------------
         1          1          1                         1,5
         5         12          1                           2
         5         13          1                           2

SQL>