LeetCode力扣-数据库511

511题干

写一条 SQL 查询语句获取每位玩家 第一次登陆平台的日期。

 

SQL架构

 

Create table If Not Exists Activity (player_id int, device_id int, event_date date, games_played int)
Truncate table Activity
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-03-01', '5')
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-05-02', '6')
insert into Activity (player_id, device_id, event_date, games_played) values ('2', '3', '2017-06-25', '1')
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '1', '2016-03-02', '0')
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '4', '2018-07-03', '5')

 

示例

我的题解

SELECT DISTINCT player_id, MIN(event_date) AS first_login
FROM Activity
GROUP BY player_id

 

优秀题解

select player_id, event_date as first_login from (
select
player_id,
event_date,
dense_rank()
over(partition by player_id order by event_date) as 排名
from activity
) as temp where 排名 = 1;
解析
使用 dense_rank 函数按照 player_id 和 event_date 进行排序,并算出排名将其作为临时表 temp
查询临时表 temp,筛选出 排名 = 1 数据

作者:uccs
链接:https://leetcode.cn/problems/game-play-analysis-i/solution/liang-chong-jie-ti-si-lu-by-uccs-5gpc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 


 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-duplicate-emails
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2022-05-16 00:00  Fancy[love]  阅读(29)  评论(0编辑  收藏  举报