【问题标题】:mysql get max value after min valuemysql在最小值后获取最大值
【发布时间】:2021-06-02 14:14:53
【问题描述】:

在mysql表中,我想得到最小值之后的最大值。

SELECT * from `table`
result:

id  date                 value
--  -------------------  -----
1   2021-03-03 13:14:05  1.15
2   2021-03-03 13:14:06  1.32
3   2021-03-03 13:14:07  1.40
4   2021-03-03 13:14:08  1.38
5   2021-03-03 13:14:01  1.55
6   2021-03-03 13:14:02  1.60
7   2021-03-03 13:14:03  1.30
8   2021-03-03 13:14:04  1.10

但我必须按日期排序,

SELECT * from `table` ORDER by date
result:

id  date                 value
--  -------------------  -----
5   2021-03-03 13:14:01  1.55
6   2021-03-03 13:14:02  1.60 # this is not target row.
7   2021-03-03 13:14:03  1.30
8   2021-03-03 13:14:04  1.10 # min value
1   2021-03-03 13:14:05  1.15
2   2021-03-03 13:14:06  1.32
3   2021-03-03 13:14:07  1.40 # this is TARGET row.(max after min)
4   2021-03-03 13:14:08  1.38

按日期排序后, 我想得到最小值(1.10)之后的最大值(1.40)

id 6,值 1.60 不是目标行。 因为这个最大值(1.60)不是在最小值(1.10)之后

id 3,值 1.40 是目标行。 因为这个最大值(1.40)在最小值(1.10)之后 最小值之前的所有值都应该被忽略。 我想得到这一行(id 3, value 1.40)

我需要哪个 sql 查询?

【问题讨论】:

  • 您能否编辑问题以更清楚地显示目标结果?

标签: mysql max min


【解决方案1】:

我会使用子查询和限制。表名和列名只是一个示例,因此请将其调整为您正确的表名和列。祝你好运

select * from table 
inner join (
    select id as minvalid, min(value) as minvalue from table 
) subQuery on value > minvalue 
limit 1

【讨论】:

  • 这是不正确的。 select id as minvalid, min(value) 可能返回与包含min(value) 的行无关的minvalid。您需要添加另一个层来获取相关 ID,就像 zedfoxus 所做的那样。
  • 确认同意,谢谢指出。
【解决方案2】:

你可以这样运行:

select * from t
where vl = (
  select max(vl) from t
  where dt > (
    select dt from t where vl = (select min(vl) from t)
  )
);

+------+---------------------+------+
| id   | dt                  | vl   |
+------+---------------------+------+
|    3 | 2021-03-03 13:14:07 | 1.40 |
+------+---------------------+------+

想法是首先使用select min(vl) from t 从表t 中获取最小值。

然后,我们使用select dt from t where vl = (select min(vl) from t) 获取看到该值的日期。

然后,我们得到在该日期之后显示的最大值:

select max(vl) from t
  where dt > (
    select dt from t where vl = (select min(vl) from t)
  )

然后,我们得到具有该最大值的行。

【讨论】:

    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2020-06-24
    • 2021-11-02
    • 1970-01-01
    • 2016-04-14
    • 2012-08-23
    相关资源
    最近更新 更多