【SQL】sum() over&row_number() over用法

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值