2016-03-01 45 views
-2

我有一個表如何獲得第一和第二最新日期的時間字段

id Name  date_time    package 
1  abc 2016-02-25 11:29:00   0 
2  xyz 2016-02-25 11:29:00   0 
3  abc 2016-02-24 11:29:00   1 
4  xyz 2016-02-24 11:29:00   1 
5  abc 2016-02-23 11:29:00   1 
6  xyz 2016-02-23 11:29:00   1 

我的結果將是包含導致

name  latest_date   latest_date1 
abc  2016-02-25 11:29:00  2016-02-24 11:29:00 
xyz  2016-02-25 11:29:00 2016-02-24 11:29:00 
+0

考慮處理在應用程序級別的代碼數據顯示的問題。 – Strawberry

+0

@Jens即使我對這個問題沒有任何想法 –

+0

你想打印兩個最新的日期嗎? – NAIT

回答

1

形式給一個虛擬錶行編號爲Name,每組編號爲date_time。然後選擇latest_date和RN = RN 2 = 1 latest_date1

查詢

select t.Name as table_name, 
max(case when t.rn = 1 then t.date_time end) as latest_date, 
max(case when t.rn = 2 then t.date_time end) as latest_date1 
from (
    select id, name, date_time, 
    (
    case name when @curA 
    then @curRow := @curRow + 1 
    else @curRow := 1 and @curA := name end 
) + 1 as rn 
    from your_table_name t, 
    (select @curRow := 1, @curA := '') r 
order by name, date_time desc 
)t 
group by t.Name; 

SQL Fiddle demo

相關問題