在MySQL中,如果想要表示某个日期(假设存储为DATE类型)的后一天,你可以使用DATE_ADD()函数或者通过加法操作符(+ INTERVAL)来实现。以下是两种方法的示例:
MySQL某日期后一天表示方法
使用 DATE_ADD() 函数
SELECT DATE_ADD(your_date_column, INTERVAL 1 DAY) AS next_day
FROM your_table;
使用 + INTERVAL
SELECT your_date_column + INTERVAL 1 DAY AS next_day
FROM your_table;
两种方法都会返回your_date_column中每个日期值的后一天。
示例
官方解法
力扣官方解题方法很标准:力扣官方解题
首先,求出所有用户首次登录的第二天的时间。方法是查询出 Activity 表中每个用户的第一天时间,并加上 1。
select player_id, DATE_ADD(MIN(event_date), INTERVAL 1 DAY) as second_date
from Activity
group by player_id
将此表命名为 Expected。随后我们要从 Activity 表中查询 event_date 与 Expected.sencond_date 重叠的部分,注意此判定要限定在用户相同的前提下。这部分用户即为在首次登录后第二天也登录了的用户:
select Activity.player_id as player_id
from (
select player_id, DATE_ADD(MIN(event_date), INTERVAL 1 DAY) as second_date
from Activity
group by player_id
) as Expected, Activity
where Activity.event_date = Expected.second_date and Activity.player_id = Expected.player_id
将此表命名为 Result。随后我们只需要得到 Result 表中用户的数量,以及 Activity 表中用户的数量,相除并保留两位小数即可。
select IFNULL(round(count(distinct(Result.player_id)) / count(distinct(Activity.player_id)), 2), 0) as fraction
将以上三步组合起来,得最终的查询:
select IFNULL(round(count(distinct(Result.player_id)) / count(distinct(Activity.player_id)), 2), 0) as fraction
from (
select Activity.player_id as player_id
from (
select player_id, DATE_ADD(MIN(event_date), INTERVAL 1 DAY) as second_date
from Activity
group by player_id
) as Expected, Activity
where Activity.event_date = Expected.second_date and Activity.player_id = Expected.player_id
) as Result, Activity
快速解法
大佬的更高效解法:高效解法
select round(avg(a.event_date is not null), 2) fraction
from
(select player_id, min(event_date) as login
from activity #这个子查询为每个玩家找到最早的event_date(标记为login)
group by player_id) p
left join activity a
on p.player_id=a.player_id and datediff(a.event_date, p.login)=1
#activity表中的event_date是login日期的后一天(使用datediff函数计算)
这个解法的精髓在于:
avg(a.event_date is not null) = sum(if(a.event_date is not null, 1, 0))/count(*)
avg(a.event_date is not null):它是一个布尔表达式,当a.event_date不为空时返回1,否则返回0。因此,这个平均值实际上是在计算满足连接条件的行数(即login日期的后一天有活动的玩家数)与所有玩家的比例。