事件表:Events+---------------+---------+| Column Name | Type |+---------------+---------+| business_id | int || event_type | varchar || occurences | int |+---------------+---------+此表的主键是 (business_id, event_type)。表中的每一行记录了某种类型的事件在某些业务中多次发生的信息。写一段 SQL 来查询所有活跃的业务。如果一个业务的某个事件类型的发生次数大于此事件类型在所有业务中的平均发生次数,并且该业务至少有两个这样的事件类型,那么该业务就可被看做是活跃业务。查询结果格式如下所示:Events table:+-------------+------------+------------+| business_id | event_type | occurences |+-------------+------------+------------+| 1 | reviews | 7 || 3 | reviews | 3 || 1 | ads | 11 || 2 | ads | 7 || 3 | ads | 6 || 1 | page views | 3 || 2 | page views | 12 |+-------------+------------+------------+结果表+-------------+| business_id |+-------------+| 1 |+-------------+'reviews'、 'ads' 和 'page views' 的总平均发生次数分别是 (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5。id 为 1 的业务有 7 个 'reviews' 事件(大于 5)和 11 个 'ads' 事件(大于 8),所以它是活跃业务。来源:力扣(LeetCode)链接:https://leetcode.cn/problems/active-businesses
#测试数据Create table If Not Exists Events (business_id int, event_type varchar(10), occurences int);insert into Events (business_id, event_type, occurences) values ('1', 'reviews', '7');insert into Events (business_id, event_type, occurences) values ('3', 'reviews', '3');insert into Events (business_id, event_type, occurences) values ('1', 'ads', '11');insert into Events (business_id, event_type, occurences) values ('2', 'ads', '7');insert into Events (business_id, event_type, occurences) values ('3', 'ads', '6');insert into Events (business_id, event_type, occurences) values ('1', 'page views', '3');insert into Events (business_id, event_type, occurences) values ('2', 'page views', '12');
#方法一:使用子查询withtmp1 as (selecta.event_type,avg(a.occurences) avg_occurencesfrom Events agroup by a.event_type)selectb.business_idfrom Events binner join tmp1 con b.event_type = c.event_typeand b.occurences > c.avg_occurencesgroup by b.business_idhaving count(1)>=2;#方法二:使用分析函数select b.business_idfrom(selecta.business_id,a.occurences,avg(a.occurences) over(partition by a.event_type) as avg_occurencesfrom events a)bwhere b.occurences > b.avg_occurencesgroup by 1having count(1) > 1;#方法三:使用自关联SELECTc.business_idfrom(SELECTa.business_id,a.event_typeFROM Events ainner join Events bon a.event_type = b.event_typegroup by a.business_id,a.event_typehaving max(a.occurences) > avg(b.occurences))cgroup by c.business_idhaving count(1)>=2;

文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




