在 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,值 1.40)
我需要哪个 sql 查询?
你可以运行这样的东西:
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 |
+------+---------------------+------+
这个想法是t
首先使用select min(vl) from 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)
)
然后,我们得到具有该最大值的行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句