mysql - 如何取最大值和次大值做减法?

标签 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 |

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

这是我的 sql fiddle : http://sqlfiddle.com/#!9/45e06e/6

最佳答案

你能试试这个吗?

select event_type, (value - (select e2.value from events e2 where e2.event_type = e1.event_type and e2.date != e1.date order by date desc limit 1)), max(date)
from events e1
group by event_type
having (count(event_type) >= 2);

关于mysql - 如何取最大值和次大值做减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979268/

相关文章:

mysql - 计算一年中每个月的三个级别(L1,L2,L3)列和状态 P 的行数

sql - 如何在 SQL SERVER 中仅提取电子邮件 ID

sql - 用于混淆/清除生产数据的简单工具/步骤

php - Mysql_query 错误

mysql - SQL Error : 1054, SQLState : 42S22 , Spring Boot jpa 应用程序中 'NaN' 中的未知列 'field list'

php - 取消设置 mysql 结果

mysql - 按多个重复行排序,然后删除

mysql - 如何限制 MySQL 中的连接?

python - Odoo E8103 : SQL injection risk. 如果可以,请使用参数

php - 使用 ORDER BY DESC 排名,但更新列