题解 | #每篇文章同一时刻最大在看人数#

每篇文章同一时刻最大在看人数

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

# ## 最大同时在线人数:(有一个固定的套路,先记住甚至背下来就行)
# ## 第一步 将用户的进入时间单列出来,记为1,将离开时间单列出来记为-1
# ## 第二步 使用窗口函数对计数 1或-1 进行累计求和,但同一时刻有进有出先算进后算出:先按照时间排序,然后按照计数排序
# ## 第三步 在每个分组里面求最大的累计和 就是最多同时在线的人数了

# ## 第一步:  将in_time和out_time统一记为dt列,值分别为1和-1 记为diff列
# SELECT
#     artical_id,in_time AS dt,1 AS diff
# FROM tb_user_log
# WHERE artical_id != 0
# UNION ALL
# SELECT
#     artical_id,out_time AS dt, -1 AS diff
# FROM tb_user_log
# WHERE artical_id != 0
# ORDER BY artical_id,df

# ## 第二步: 加入窗口函数来累加
# SELECT
#     artical,dt,SUM(diff) OVER(PARTITION BY artical_id ORDER BY dt) AS instant_viewer_cnt
# FROM(
#     SELECT
#         artical_id,in_time AS dt,1 AS diff
#     FROM tb_user_log
#     WHERE artical_id != 0
#     UNION ALL
#     SELECT
#         artical_id,out_time AS dt, -1 AS diffFROM tb_user_log
#     WHERE artical_id != 0
#     ORDER BY artical_id,df
# )

## 第三步: 取出最大值
SELECT 
    artical_id,MAX(instant_viewer_cnt) AS max_uv
FROM(
    SELECT
    artical_id,dt,SUM(diff) OVER(PARTITION BY artical_id ORDER BY dt,diff DESC) AS instant_viewer_cnt
    FROM(
        SELECT
            artical_id,in_time AS dt,1 AS diff
        FROM tb_user_log
        WHERE artical_id != 0
        UNION ALL
        SELECT
            artical_id,out_time AS dt, -1 AS diff
        FROM tb_user_log
        WHERE artical_id != 0
         )t1
     )t2
GROUP BY artical_id
ORDER BY max_uv DESC

全部评论

相关推荐

AFBUFYGRFHJLP:直接去美帝试试看全奖phd吧
点赞 评论 收藏
分享
菜菜咪:1. 可以使用简历网站的模版,美观度会更好一点 2. 邮箱可以重新申请一个,或者用qq邮箱的别名,部分hr可能会不喜欢数字邮箱 3. 项目经历最好分点描述,类似的项目很多,可以参考一下别人怎么写的 4. 自我评价可加可不加,技术岗更看重技术。最后,加油,优秀士兵
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-27 10:48
点赞 评论 收藏
分享
评论
点赞
1
分享
牛客网
牛客企业服务