具体来说,我有多次与会话相关联的点击,并且每次点击都有一个日期时间。对于每个会话,我想选择字段'first_click_datetime','second_click_datetime','third_click_datetime'等。
到目前为止,我有这样的事情:
SELECT session_id,
min(click_datetime) as first_click_datetime,
CASE
when total_number_of_clicks = 2 then max(click_datetime)
/* when total_number_of_clicks >2 then ???? */
else null
END as second_click_datetime
FROM table1 GROUP BY 1;
如何获得第二,第三,第四等click_datetime?
谢谢!
答案 0 :(得分:1)
SELECT session_id,
(
SELECT click_datetime
FROM table1 t1
WHERE t1.session_id = td.session_id
ORDER BY
session_id DESC, click_datetime DESC, id DESC
LIMIT 1
) AS first_click,
(
SELECT click_datetime
FROM table1 t1
WHERE t1.session_id = td.session_id
ORDER BY
session_id DESC, click_datetime DESC, id DESC
LIMIT 1, 1
) AS second_click,
(
SELECT click_datetime
FROM table1 t1
WHERE t1.session_id = td.session_id
ORDER BY
session_id DESC, click_datetime DESC, id DESC
LIMIT 2, 1
) AS third_click
FROM (
SELECT DISTINCT session_id
FROM table1
) td
在(session_id, click_datetime, id)
上创建一个索引,以便快速工作。