如何翻译以下代码,使其在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的期望输出
代码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
答案 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