LeetCode——Question 534: Gameplay Analysis ||| (Data Analysis SQL)

topic

Table: Activity

Column Name Type
player_id int
device_id int
event_date date
games_played int

(player_id, event_date) is the primary key of this table.
This table shows player activity for certain games.
Each row is a record of a player who logged in and played a lot of games (probably 0 ) on a certain day before logging out on a certain device.
Write a SQL query that reports simultaneously for each group of players and dates, as well as how many games the players have played so far. That is, the total number of games played by the player before this date. See examples for details.

The query result format is as follows:
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

For the player with ID 1, a total of 5+6=11 games were played on 2016-05-02, and a total of 5+6+1=12 games were played on 2017-06-25.
For the player with ID 3, a total of 0+5=5 games were played on 2018-07-03.
Please note that for each player, we only care about the player's login date.

Ideas
  1. Self-join, get the overall table in the figure.
  2. Find the data whose time is in front of itself, as shown by the gray pen in the figure.
  3. Usesum() with grouping statementgroup by Group and sum the two primary keys, as outlined by the brown dashed circle in the figure.

Insert image description here

Code that runs successfully
select
    a.player_id,
    a.event_date,
    sum(b.games_played) as games_played_so_far
from
    activity as a
    inner join activity as b
    on a.player_id=b.player_id and b.event_date<=a.event_date
group by
    a.player_id,a.event_date
operation result

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45398231/article/details/122603568