欢迎访问yhm138的博客园博客, 你可以通过 [RSS] 的方式持续关注博客更新

MyAvatar

yhm138

HelloWorld!

MySQL 用户自定义变量,面向过程编程解决"连续天数"的问题

题目地址

https://www.nowcoder.com/practice/e080f8a685bc4af3b47749ca3310f1fd

代码

牛客网的Mysql是8.0,MySQL 用户变量在8.0.13后不可用。
这题仍然可以使用用户变量过程编程的方式解决"连续天数"的问题。

思路就是先按照author_id, answer_date排序,之后一行一行处理。

# 代码由chatgpt给出
# Keep in mind that MySQL user variables are deprecated since MySQL 8.0.13, so using window functions might be a better approach for future-proofing your query.

WITH answer_dates AS (
    SELECT

        #------------只需要修改里面的逻辑就行。注意语句是“顺序执行”的-------------------------------
        answer_date,
        author_id,
        IF(answer_date = @prev_date + INTERVAL 1 DAY AND author_id = @prev_author_id, @consec_days := @consec_days + 1, @consec_days := 1) AS consec_days,
        @prev_date := answer_date,
        @prev_author_id := author_id
        #-------------只需要修改里面的逻辑就行。注意语句是“顺序执行”的------------------------------
    FROM
        (SELECT @prev_date := NULL, @prev_author_id := NULL, @consec_days := 1) vars,
        (SELECT answer_date, author_id FROM answer_tb ORDER BY author_id, answer_date) ordered_dates
)


select t1.author_id,t2.author_level as author_level,
CAST(t1.max_consec_days AS UNSIGNED INT) AS days_cnt   #注意这里的CAST一定一定不能省略!!!!!
from
(
    SELECT
        author_id,
        MAX(consec_days) AS max_consec_days
    FROM
        answer_dates
    GROUP BY
        author_id
    HAVING
        max_consec_days >= 3
)t1
join author_tb t2
on t2.author_id=t1.author_id

posted @ 2023-03-22 21:42  yhm138  阅读(18)  评论(0编辑  收藏  举报