如何根据concert_id计算出席率?
到目前为止,我所做的就像这样
select concert_id, event_id, count(customer_id) attendance,
case when concert_id = 1
then (select count(customer_id)/count(concert_id)
from booking where concert_id=1)
end as avg_attendance_each_concert
from booking
group by event_id, concert_id
order by event_id;
结果
CONCERT_ID EVENT_ID ATTENDANCE AVG_ATTENDANCE_EACH_CONCERT
---------- ---------- ---------- ---------------------------
1 1 1 3
1 2 2 3
2 3 2
2 4 1
3 5 2
3 6 2
4 8 2
4 9 2
5 11 4
5 12 1
5 13 1
如何让AVG_ATTENDANCE_EACH_CONCERT变成这样?
CONCERT_ID EVENT_ID ATTENDANCE AVG_ATTENDANCE_EACH_CONCERT
---------- ---------- ---------- ---------------------------
1 1 1 1.5 --> 3 attendance / 2 same concert_id
1 2 2 1.5
2 3 2 1.5 --> 3 attendance / 2 same concert_id
2 4 1 1.5
3 5 2 2 --> 4 attendance / 2 same concert_id
3 6 2 2
4 8 2 2 --> 4 attendance / 2 same concert_id
4 9 2 2
5 11 4 2 --> 6 attendance / 3 same concert_id
5 12 1 2
5 13 1 2
因为我想表明哪个活动的平均出勤率低于平均水平
答案 0 :(得分:1)
AVG的分析形式如何?
(顺便说一下,你的CONCERT_ID = 5的例子是错的; 6/3 = 2,而不是3)。
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 select concert_id, event_id, count(customer_id) attendance,
19 avg(count(*)) over (partition by concert_id) avg_attendance_each_concert
20 from booking
21 group by concert_id, event_id
22 order by event_id;
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
7 rows selected.
SQL>