田灬禾-不忘初心,方得始終

寧靜以逸遠,心靜而無邪

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

引自:https://mp.weixin.qq.com/s?__biz=MzA3MTg4NjY4Mw==&mid=2457306345&idx=3&sn=4336394315ace4827d31b2214994d63f&chksm=88a596ddbfd21fcbf16c8bcb2dd0a6fb3c1078878d6240293d6089c1b0921a2994c936df2f12&mpshare=1&scene=1&srcid=&sharer_sharetime=1590455870027&sharer_shareid=18c156b37f741bf9989098e28bf33e09&exportkey=AS1mHU5CJ3PCf5wTjsP7Gzo%3D&pass_ticket=FAFpK24YPTbtB0QJp5QUlKxHUokdkDrTGw8f6H0%2FT%2FAbyRMz3YG%2FDYhi9xF7r2Ja#rd

感谢出题者,如有冒犯,请与我联系,希望和大家一起学习交流。(目前使用oracle数据库环境编写sql)

 

题目

表user_time中的字段时user_id,time(用户访问时间)

 

 

 

求每个用户相邻两次浏览时间之差小于三分钟的次数 预计结果如下:

 

 

该如何写查询?

读者可以试着自己思考写下,再往下翻... 如有不同解题方式,欢迎大家一起交流。

 

 

 

 

 

 

运用分析函数或者lag函数

sys@ESWIFT> WITH T AS
  2   (SELECT '1' USER_ID,
  3           TO_DATE('2020-05-26 21:13:07', 'yyyy-MM-dd hh24:mi:ss') TIMES
  4      FROM DUAL
  5    UNION ALL
  6    SELECT '1' USER_ID,
  7           TO_DATE('2020-05-26 21:15:26', 'yyyy-MM-dd hh24:mi:ss') TIMES
  8      FROM DUAL
  9    UNION ALL
 10    SELECT '1' USER_ID,
 11           TO_DATE('2020-05-26 21:17:44', 'yyyy-MM-dd hh24:mi:ss') TIMES
 12      FROM DUAL
 13    UNION ALL
 14    SELECT '2' USER_ID,
 15           TO_DATE('2020-05-12 21:14:06', 'yyyy-MM-dd hh24:mi:ss') TIMES
 16      FROM DUAL
 17    UNION ALL
 18    SELECT '2' USER_ID,
 19           TO_DATE('2020-05-12 21:18:19', 'yyyy-MM-dd hh24:mi:ss') TIMES
 20      FROM DUAL
 21    UNION ALL
 22    SELECT '2' USER_ID,
 23           TO_DATE('2020-05-12 21:20:36', 'yyyy-MM-dd hh24:mi:ss') TIMES
 24      FROM DUAL
 25    UNION ALL
 26    SELECT '3' USER_ID,
 27           TO_DATE('2020-05-21 21:16:51', 'yyyy-MM-dd hh24:mi:ss') TIME
 28      FROM DUAL
 29    UNION ALL
 30    SELECT '4' USER_ID,
 31           TO_DATE('2020-05-16 22:22:08', 'yyyy-MM-dd hh24:mi:ss') TIME
 32      FROM DUAL
 33    UNION ALL
 34    SELECT '4' USER_ID,
 35           TO_DATE('2020-05-02 21:17:22', 'yyyy-MM-dd hh24:mi:ss') TIME
 36      FROM DUAL
 37    UNION ALL
 38    SELECT '4' USER_ID,
 39           TO_DATE('2020-05-30 15:15:44', 'yyyy-MM-dd hh24:mi:ss') TIME
 40      FROM DUAL
 41    UNION ALL
 42    SELECT '4' USER_ID,
 43           TO_DATE('2020-05-30 15:17:57', 'yyyy-MM-dd hh24:mi:ss') TIME
 44      FROM DUAL)
 45  SELECT USER_ID, SUM(CN) CNT
 46    FROM (SELECT T.*,
 47                 CASE
 48                     WHEN (TIMES - MAX(TIMES)
 49                           OVER(PARTITION BY USER_ID ORDER BY TIMES
 50                                ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)) * 24 * 60 < 3 THEN
 51                      1
 52                     ELSE
 53                      0
 54                 END CN
 55            FROM T)
 56   GROUP BY USER_ID
 57  /

USER_ID           CNT
---------- ----------
1                   2
2                   1
3                   0
4                   1

 

posted on 2020-05-26 15:05  田灬禾  阅读(299)  评论(0编辑  收藏  举报