如何在datetime字段中获取第一个和第二个最新日期

时间:2016-03-01 11:36:27

标签: mysql

我有一张桌子

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 

1 个答案:

答案 0 :(得分:1)

根据date_time的每个Name组的降序排列一个行号。然后为latest_date选择rn = 1,为latest_date1选择rn = 2

<强>查询

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