【问题标题】:In a MySQL GROUP BY, how can one select the nth value --not the max or min, but 2nd, for example?例如,在 MySQL GROUP BY 中,如何选择第 n 个值——不是最大值或最小值,而是第二个?
【发布时间】:2012-05-26 00:20:33
【问题描述】:

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

如何获取第 2 次、第 3 次、第 4 次等 click_datetime?

谢谢!

【问题讨论】:

标签: mysql select group-by denormalization


【解决方案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) 上创建一个索引以使其快速工作。

【讨论】:

  • 这里的“id”字段是什么?这看起来可以工作,但实际上会使我的代码变得非常混乱;当我在我的 sql 代码中说“table1”时,它实际上是与其他选择连接的选择。不过,谢谢!
  • @Marina,您可以创建一个视图table1,将其称为表格。
猜你喜欢
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
相关资源
最近更新 更多