如何获得最大值和第二大值进行减法?

时间:2016-03-14 03:54:03

标签: mysql sql

我有一张表如下:

| event_type | value |                    date |
|------------|-------|-------------------------|
|          2 |    -7 | March, 01 2016 09:00:00 |
|          2 |     4 | March, 01 2016 08:00:00 |
|          2 |    21 | March, 01 2016 07:00:00 |
|          3 |    10 | March, 01 2016 06:00:00 |
|          3 |     8 | March, 01 2016 05:00:00 |
|          4 |    21 | March, 01 2016 04:00:00 |

我希望得到每个event_type的最大值和第二大值来进行减法,如下所示:

| event_type | value |
|------------|-------|
|          2 |   -11 |
|          3 |     2 |

目前,我只能获得每个event_type的最大值,如下所示:

select event_type, value, max(date)
from events
group by event_type
having (count(event_type) >= 2);

| event_type | value |               max(date) |
|------------|-------|-------------------------|
|          2 |    -7 | March, 01 2016 09:00:00 |
|          3 |    10 | March, 01 2016 06:00:00 |

我想我需要知道如何获得第二大价值。因此,我可以做减法。

这是我的小提琴: http://sqlfiddle.com/#!9/45e06e/6

4 个答案:

答案 0 :(得分:1)

你能试试吗?

\r

答案 1 :(得分:0)

如果你可以使用Window Functions(你没有提到你的数据库),这很容易:

SQL> select value from ( 
         select 
            value, 
            row_number() 
               over(partition by event_type order by value desc) as rn 
         from afuncts.employees )x 
     where rn <= 2 ;

答案 2 :(得分:0)

此代码有效吗?

select event_type, value from 
(select e.*, ROWNUM rnum from events e order by value desc) where rnum = 2;

答案 3 :(得分:0)

这是我的答案:

select 
  event_type, 
  (   
     (select 
        e1.value as first_value
      from 
        events e1
      where 
        e1.event_type = e.event_type and 
        e1.date = e.date 
      order by date desc
        limit 1
     ) -   
     (select 
        e2.value as second_value
      from 
        events e2
      where 
        e2.event_type = e.event_type and 
        e2.date < e.date 
      order by date desc
        limit 1
     )
  )
from 
  (     
    select 
      *
    from 
      events
    order by 
      date desc
  ) e
group by event_type
having (count(event_type) >= 2);

sql我可以得到最新的值:

select 
  e1.value as first_value
from 
  events e1
where 
  e1.event_type = e.event_type and 
  e1.date = e.date 
order by date desc
  limit 1

sql我可以获得第二个最新值:

select 
  e2.value as second_value
from 
  events e2
where 
  e2.event_type = e.event_type and 
  e2.date < e.date 
order by date desc
  limit 1

因此,我可以使用这些值进行减法。

这是我的sqlfiddle:

http://sqlfiddle.com/#!9/14982/19