以游戏玩法分析为例用Mysql求累计和
问题描述
Column Name | Type |
---|---|
player_id | int |
device_id | int |
event_date | date |
games_played | int |
(player_id,event_date)是表格Activity的主键。这张表显示了某些游戏的玩家的活动情况。每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0 )。
编写一个 SQL 查询,同时报告每组玩家和日期,以及玩家到目前为止玩了多少游戏。也就是说,在此日期之前玩家所玩的游戏总数。
示例
Activity table:
player_id | device_id | event_date | games_played |
---|---|---|---|
1 | 2 | 2016-03-01 | 5 |
1 | 2 | 2016-05-02 | 6 |
1 | 3 | 2017-06-25 | 1 |
3 | 1 | 2016-03-02 | 0 |
3 | 4 | 2018-07-03 | 5 |
Result table:
player_id | event_date | games_played_so_far |
---|---|---|
1 | 2016-03-01 | 5 |
1 | 2016-05-02 | 11 |
1 | 2017-06-25 | 12 |
3 | 2016-03-02 | 0 |
3 | 2018-07-03 | 5 |
解答
# Write your MySQL query statement below
select a1.player_id, a1.event_date, sum(a2.games_played) as games_played_so_far
from Activity as a1
inner join Activity as a2
on (a1.event_date >= a2.event_date and a1.player_id=a2.player_id)
group by a1.player_id, a1.event_date
order by a1.player_id;
或用窗口函数sum()
select player_id, event_date,
sum(games_played) over(partition by player_id order by event_date asc) as games_played_so_far
from Activity;
分析
用mysql求累计和主要是:
a1.event_date >= a2.event_date
然后对a2进行sum求和即可。
(第一次解的时候,忘了对 a1.player_id 分组)
用sum()做窗口函数也能求累计和!
参考:leetcode题库