我有一张桌子
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 :(得分: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;