2016-03-01 42 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

相关问题