1.SUM(column) OVER(PARTITION BY column1 ORDER BY column2)
SUM(column) OVER() :求和
SUM(column) OVER(PARTITION BY column1) :分组加法
SUM(column) OVER(PARTITION BY column1 ORDER BY column2):分组累加
2.ROW_NUMBER() OVER(PARTITION BY column1 ORDER BY column2)
ROW_NUMBER() OVER():整体编号
ROW_NUMBER() OVER(PARTITION BY column1 ORDER BY column2):分组编号
eg.leetcode550
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 the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.
Write an SQL query to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
with num as (SELECT *,row_number() over(partition by player_id order by event_date) r
FROM activity)
SELECT CAST(COUNT(distinct a1.player_id)/(SELECT COUNT(DISTINCT player_id) from activity) AS DECIMAL(10,2)) AS fraction
FROM num a1 left join num a2
ON a1.r = (a2.r)-1 and a1.player_id=a2.player_id WHERE a2.event_date-a1.event_date=1
and (a1.player_id,a1.event_date) IN
(SELECT player_id,MIN(event_date) FROM activity GROUP BY player_id)