如何选择最后一个但最后一个记录

时间:2018-03-15 22:37:52

标签: mysql sql

我有一个包含3列id, type, value的表格,如下图所示。

example

我要做的是进行查询以获取此格式的数据:

type     previous  current
month-1  666       999
month-2  200       15
month-3  0         12

我做了这个查询,但它只获得了最后一个值

select * 
  from statistics 
 where id in (select max(id) from statistics group by type)    
 order 
    by type

enter image description here

编辑:实例http://sqlfiddle.com/#!9/af81da/1

谢谢!

2 个答案:

答案 0 :(得分:4)

我会把它写成:

select s.*,
       (select s2.value
        from statistics s2
        where s2.type = s.type
        order by id desc
        limit 1, 1
       ) value_prev
from statistics s
where id in (select max(id) from statistics s group by type) order by type;

对于statistics(type, id)上的索引,这应该相对有效。

答案 1 :(得分:1)

select 
type,
ifnull(max(case when seq = 2 then value end),0 ) previous,
max( case when seq = 1 then value end ) current
from
(
select *, (select count(*)
           from statistics s 
           where s.type = statistics.type
           and s.id >= statistics.id) seq
from statistics ) t
where seq <= 2
group by type
相关问题