[英]How to select MAX/MIN in MySQL with dynamic between clause
Assume a table with two columns t (a string with TimeStamps) and v (decimal).假设一个表有两列t (带有时间戳的字符串)和v (十进制)。 For each t I want to query the MAXIMUM of the value v in a certain range defined by the current t .
对于每个t我想在当前t定义的特定范围内查询值v的最大值。
How can i transfer below statement to proper SQL?如何将以下语句转移到正确的 SQL?
select t, max(v for t between t-2MIN and t+2min) from table_name;
Example:例子:
Assume below table.假设下表。
t![]() |
v ![]() |
---|---|
1 ![]() |
3 ![]() |
2 ![]() |
2 ![]() |
3 ![]() |
5 ![]() |
4 ![]() |
4 ![]() |
5 ![]() |
8 ![]() |
6 ![]() |
1 ![]() |
I need an SQL-statement which gives me (for eg a width 2 : max(v for t between t-2 and t+2)
) the following result我需要一个 SQL 语句,它给我(例如宽度2 :
max(v for t between t-2 and t+2)
)以下结果
t![]() |
v ![]() |
---|---|
1 ![]() |
5 ![]() |
2 ![]() |
5 ![]() |
3 ![]() |
8 ![]() |
4 ![]() |
8 ![]() |
5 ![]() |
8 ![]() |
6 ![]() |
8 ![]() |
Join the table with itself using the range as the joining condition.使用范围作为连接条件将表与自身连接起来。
SELECT t1.t, MAX(t2.v) AS max_v
FROM table_name AS t1
JOIN table_name AS t2 ON t2.t BETWEEN t1.t - 2 AND t1.t + 2
GROUP BY t1.t
If you use MySQL 8.x I think you should be able to do it using window functions, but I don't know the proper syntax for this.如果您使用 MySQL 8.x,我认为您应该能够使用 window 函数来做到这一点,但我不知道正确的语法。
In MySql 8 you can use a MAX OVER
with rows between a range.在 MySql 8 中,您可以使用
MAX OVER
与范围之间的行。
select t
, max(v) over (order by t rows
between 2 preceding and 2 following) v
from table_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.