2012-05-18 90 views
1

具體來說,我有多個與會話關聯的點擊,並且每個點擊都有一個日期時間。對於每個會話,我希望選擇字段'first_click_datetime','second_click_datetime','third_click_datetime'等。在MySQL GROUP BY中,如何選擇第n個值 - 不是最大值或最小值,而是第2個值?

到目前爲止,我有這樣的事情:

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

您可能正在尋找排名的功能.. http://stackoverflow.com/questions/532878/how-to-perform-grouped-ranking-in-mysql –

回答

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)上創建一個索引,以便快速工作。

+0

這是什麼字段'id'在這裏?這看起來可以工作,但它實際上會讓我的代碼非常混亂;當我在我的sql代碼中說'table1'時,它實際上是與其他選擇連接的選擇。不過謝謝你! – Marina

+1

@Marina,你可以創建一個視圖'table1'作爲一個表格。 – vyegorov

相關問題