将超前/滞后功能转换为MySQL

时间:2018-04-17 04:31:48

标签: mysql sql

如何翻译以下代码,使其在MySQL中运行。我是MySQL新手,发现很难理解一些东西。

代码1:

SELECT t1.user_id,
           t1.visit_month LEAD (t1.visit_month, 1) OVER (partition BY t1.user_id ORDER BY t1.user_id, t1.visit_month)
    FROM (SELECT 
    user_id,
    month(date_time) as visit_month
FROM
    tbl_activity
    group by 1, 2
ORDER BY 1 , 2) t1;

代码1的期望输出

enter image description here

代码2:

SELECT user_id,
       visit_month,
       lead,
       lead — visit_month AS time_diff
FROM table3

代码3:

SELECT user_id,
       Visit_month,
       lag(visit_month, 1) over (partition BY user_id ORDER BY user_id, visit_month)
 FROM table

代码4:

SELECT user_id,
       visit_month,
       lag,
       visit_month — lag AS time_diff
 FROM table2

1 个答案:

答案 0 :(得分:1)

您可以通过lead()

表达lag()subquery功能
select user_id, month(date_time) as visit_month,
       month(date_time)-(select month(date_time) from tbl_activity 
                         where user_id = t.user_id and 
                         month(date_time) < month(a.date_time)
                         order by month(date_time) desc LIMIT 1) as time_diff -- This could be re-express via lag() function
from tbl_activity a
group by user_id, month(date_time); 

在上面,您需要指定< / >来表示子查询中的lead()lag()功能,并且不要忘记使用{{1} }子句

编辑(线索):

order by