目录
一,原题力扣链接
二,题干
表:
Followers
+-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) 是这个表的主键(具有唯一值的列的组合)。 该表包含一个关注关系中关注者和用户的编号,其中关注者关注用户。编写解决方案,对于每一个用户,返回该用户的关注者数量。
按
user_id
的顺序返回结果表。查询结果的格式如下示例所示。
示例 1:
输入: Followers 表: +---------+-------------+ | user_id | follower_id | +---------+-------------+ | 0 | 1 | | 1 | 0 | | 2 | 0 | | 2 | 1 | +---------+-------------+ 输出: +---------+----------------+ | user_id | followers_count| +---------+----------------+ | 0 | 1 | | 1 | 1 | | 2 | 2 | +---------+----------------+ 解释: 0 的关注者有 {1} 1 的关注者有 {0} 2 的关注者有 {0,1}
三,建表语句
Create table If Not Exists Followers(user_id int, follower_id int)
Truncate table Followers;
insert into Followers (user_id, follower_id) values ('0', '1')
insert into Followers (user_id, follower_id) values ('1', '0')
insert into Followers (user_id, follower_id) values ('2', '0')
insert into Followers (user_id, follower_id) values ('2', '1');
四,分析
- 分析
- 表 用户id 粉丝id
- 求 不同用户的粉丝数量 然后以用户排序
- 解法一:
- 以用户分组 count 粉丝数量
- 然后排序 粉丝排序
- 解法二 窗口函数
- 取出步同用户的粉丝数量 然后 以用户id分组 聚合数量
五,SQL解答
解法一,窗口函数
with t1 as (
select user_id, follower_id,
count(follower_id) over (partition by user_id order by user_id) ro
from Followers
)
select user_id,count(t1.ro) as followers_count from t1 group by user_id;
解法二 普通分组,聚合
select user_id,count(follower_id) followers_count from Followers group by user_id order by user_id;
六,验证
普通简单查询验证
窗口函数验证
七,知识点总结
- 知识点总结
- count 函数练习
- 普通的 分组,聚合 统计人数
- 窗口开窗之后 拿到具体的人数 分组后再聚合