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

相关推荐
董董灿是个攻城狮3 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki3 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb5 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
FirstFrost --sy7 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森7 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼1145147 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)7 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
独行soc7 小时前
2025年渗透测试面试题总结-2025年HW(护网面试) 33(题目+回答)
linux·科技·安全·网络安全·面试·职场和发展·护网
无聊的小坏坏8 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   9 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端