在MySQL GROUP BY中,如何选择第n个值 - 不是最大值或最小值,而是第2个值,例如?

时间:2012-05-18 12:11:06

标签: mysql select group-by denormalization

具体来说,我有多次与会话相关联的点击,并且每次点击都有一个日期时间。对于每个会话,我想选择字段'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?

谢谢!

1 个答案:

答案 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)上创建一个索引,以便快速工作。