SQL,力扣题目1126,查询活跃业务

一、力扣链接

LeetCode_1126

二、题目描述

事件表:Events

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| business_id   | int     |
| event_type    | varchar |
| occurrences   | int     | 
+---------------+---------+
(business_id, event_type) 是这个表的主键(具有唯一值的列的组合)。
表中的每一行记录了某种类型的事件在某些业务中多次发生的信息。

平均活动 是指有特定 event_type 的具有该事件的所有公司的 occurrences 的均值。

活跃业务 是指具有 多个 event_type 的业务,它们的 occurrences 严格大于 该事件的平均活动次数。

写一个解决方案,找到所有 活跃业务

三、目标拆解

四、建表语句

sql 复制代码
Create table If Not Exists Events (business_id int, event_type varchar(10), occurrences int)
Truncate table Events
insert into Events (business_id, event_type, occurrences) values ('1', 'reviews', '7')
insert into Events (business_id, event_type, occurrences) values ('3', 'reviews', '3')
insert into Events (business_id, event_type, occurrences) values ('1', 'ads', '11')
insert into Events (business_id, event_type, occurrences) values ('2', 'ads', '7')
insert into Events (business_id, event_type, occurrences) values ('3', 'ads', '6')
insert into Events (business_id, event_type, occurrences) values ('1', 'page views', '3')
insert into Events (business_id, event_type, occurrences) values ('2', 'page views', '12')

五、过程分析

1、窗口函数计算平均活动次数,不影响原字段

2、筛选有多种类型大于平均活动次数的记录

六、代码实现

sql 复制代码
with t1 as(
select business_id, event_type, occurrences, 
       avg(occurrences) over(partition by event_type) avg_occurrences
from Events
)
select business_id
from t1 where occurrences > avg_occurrences
group by business_id having count(business_id) > 1

七、结果验证

八、小结

1、CTE表达式 + 窗口函数 + group by

2、关键句:有 多个 event_type 的业务

相关推荐
京东零售技术40 分钟前
下一代 Lakehouse 智能未来新引擎 | Apache Hudi Meetup亚洲站活动回顾
算法
京东零售技术42 分钟前
NeurIPS 2025 | TANDEM:基于双层优化的数据配比学习方法
后端·算法
zmzb01031 小时前
C++课后习题训练记录Day42
开发语言·c++·算法
CoovallyAIHub1 小时前
MAR-YOLOv9:革新农业检测,YOLOv9的“低调”逆袭
深度学习·算法·计算机视觉
Mr Lee_1 小时前
Smali 文件生成dex装箱算法整合
开发语言·python·算法
LDG_AGI1 小时前
【推荐系统】深度学习训练框架(十三):模型输入——《特征索引》与《特征向量》的边界
人工智能·pytorch·分布式·深度学习·算法·机器学习
CoovallyAIHub1 小时前
如何让SAM3在医学图像上比专用模型还强?一个轻量Adapter如何让它“秒变”专家?
深度学习·算法·计算机视觉
suoge2231 小时前
热传导控制方程有限元弱形式推导-有限元编程入门
算法
希望有朝一日能如愿以偿1 小时前
力扣每日一题:统计梯形的数目
算法·leetcode·职场和发展
碧波bibo2 小时前
【算法突破】【C++】 第一篇 数组
c++·算法