【SQL】关注者数量

目录

题目

分析

代码


题目

表: 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}

分析

于每一个用户

按照用户id分组,group by user_id

返回该用户的关注者数量

count计数,count(follower_id) followers_count

按 user_id 的顺序返回结果表。

使用order by升序排列order by user_id

代码

复制代码
select user_id, count(follower_id) followers_count
from Followers
group by user_id
order by user_id
相关推荐
i220818 Faiz Ul6 小时前
计算机毕业设计|基于springboot + vue鲜花商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Apple_羊先森7 小时前
ORACLE数据库巡检SQL脚本--22、检查碎片程度最高的业务表
数据库·sql·oracle
OnYoung8 小时前
更优雅的测试:Pytest框架入门
jvm·数据库·python
山岚的运维笔记9 小时前
SQL Server笔记 -- 第85章:查询提示
数据库·笔记·sql·microsoft·sqlserver
chilavert3189 小时前
技术演进中的开发沉思-371:final 关键字(中)
java·前端·数据库
tryCbest9 小时前
SQL Server数据库
数据库·sql server
_codemonster10 小时前
PreparedStatement 和 Statement的区别
数据库·oracle
恒云客10 小时前
python uv debug launch.json
数据库·python·json