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

相关推荐
Fcy64816 分钟前
算法基础详解(五)二分算法——二分查找与二分答案
算法·二分算法
SteveSenna33 分钟前
强化学习4.1:基于价值——Q-learning
人工智能·学习·算法·机器人
少许极端35 分钟前
算法奇妙屋(四十四)-贪心算法学习之路11
java·学习·算法·贪心算法
子琦啊35 分钟前
【算法复习】数组与双指针篇
javascript·算法
ambition2024238 分钟前
斐波那契取模问题的深入分析:为什么提前取模是关键的
c语言·数据结构·c++·算法·图论
逆境不可逃1 小时前
LeetCode 热题 100 之 230. 二叉搜索树中第 K 小的元素 199. 二叉树的右视图 114. 二叉树展开为链表
算法·leetcode·职场和发展
一个有温度的技术博主1 小时前
Redis Cluster 核心原理:哈希槽与数据路由实战
redis·算法·缓存·哈希算法
wfbcg1 小时前
每日算法练习:LeetCode 15. 三数之和 ✅
算法·leetcode·职场和发展
2301_822703201 小时前
开源鸿蒙跨平台Flutter开发:跨端图形渲染引擎的类型边界与命名空间陷阱:以多维雷达图绘制中的 dart:ui 及 StrokeJoin 异常为例
算法·flutter·ui·开源·图形渲染·harmonyos·鸿蒙
y = xⁿ1 小时前
【LeetCode Hot100】双指针:分离指针
算法·leetcode