繁体   English   中英

MySQL:选择包含时间重叠的行之间最大字段的行

[英]MySQL: SELECT rows containing MAX of a field between rows with overlapping times

时间跨度:

+-----+-------+-------+-------------+
| ID  | start | stop  |   value     |
+-----+-------+-------+-------------+
|  1  |  1:00 |  3:00 |     6       |
|  2  |  5:00 |  9:00 |     3       |
|  3  |  6:00 | 10:00 |     1       |
+-----+-------+-------+-------------+

这是我想要的输出:

+-----+-------+-------+-------------+
| ID  | start | stop  |   value     |
+-----+-------+-------+-------------+
|  1  |  1:00 |  3:00 |     6       |
|  2  |  5:00 |  9:00 |     3       |
+-----+-------+-------+-------------+

在开始和停止时间戳重叠的情况下(如第 2 行和第 3 行所示),我想要包含两者之间MAX() value的行。

如果有助于澄清,这里有一种可以通过编程方式解决此问题的方法:

sort(timespans) // by 'value', highest first

results = []
for (t in timespans)
    for (row in results)

        overlap =
                (row.start < t.start && t.start < row.stop) // t.start within row
             || (row.start < t.stop && t.stop < row.stop)   // t.stop within row
             || (t.start < row.start && row.stop < t.stop)  // t encapsulates row

        if (!overlap)
            results.push(t)

您可以使用EXISTS来检查是否有重叠的另一行start / stop值和较高value的值。

像这样的东西:

select t1.id, t1.start, t1.stop, t1.value 
from your_table t1
where not exists (
  select NULL 
  from your_table t2 
  where ((t2.start between t1.start and t1.stop) or (t2.stop between t1.start and t1.stop))
  and t2.value > t1.value
)

据我所知,这里的有限信息我可能会使用 IF() 语句来查找任何重叠并将记录合并为一个,因此从 table_Name 调用 sql SELECT * 并将其保存到一个关联然后运行一个循环在记录上查找 time_a < time_b 所以 time_a = 在记录 1 中停止 time_b 是 = 开始记录 2。可能不是 IF() 可能是 for 循环然后在大括号中复制来自记录 1 和记录 2 的信息并制作一条记录的开始来自记录 1,停止来自记录 2 从您的关联中删除 2 条记录并替换为闪亮的新记录,然后使用 sql INSERT INTO 覆盖整个表,

我认为这就是你想要做的,如果我没有理解你想要实现的目标,我深表歉意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM