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 的业务

相关推荐
行者全栈架构师19 分钟前
【鸿蒙心迹】冷启动从 2.8s 优化到 0.9s——耗时拆解与数据对比实战(HarmonyOS 7.x)
前端·算法·架构
LXY_BUAA21 分钟前
《嵌入式操作系统》_framebuffer驱动_20261008
linux·运维·算法
Logic10124 分钟前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
java_nnnn25 分钟前
LeetCode刷题滑动窗口(最大连续1的个数三+将x减到0的最小操作数)Java
算法·leetcode·职场和发展
考研保研资料分享33 分钟前
普通211核专业保研经验:清华预推免录取与北大、西交面试复盘
面试·职场和发展
背调与用工合规夏律师1 小时前
知情同意在跨境提供与境外接收方信息上的证据要求
职场和发展
bnmoel1 小时前
C++ 基础入门篇(六)类和对象-第三篇:运算符重载
开发语言·c++·算法·语法·运算符重载
wuyk5551 小时前
28 搜索引擎索引更新:从 LSM Tree 到布隆过滤器的高效实现
stm32·单片机·嵌入式硬件·算法
我命由我123451 小时前
LRU 缓存淘汰策略
数据结构·redis·学习·mysql·算法·缓存·学习方法
SunShaoLu1 小时前
流程图工具怎么选:5 款产品的技术对比与选型实践
人工智能·职场和发展·流程图·效率工具