具有最高组合相邻值的MySQL搜索

时间:2013-03-26 15:34:51

标签: mysql database search

depth   ktim
6999.0  576.46
6999.5  892.10
7000.0   10.12
7000.5   22.07
7001.0  186.55
7001.5  577.98
7002.0  799.42
7002.5  334.15
7003.0   99.43
7003.5  111.43
7004.0   41.94

所以我有一个庞大的数据库表,上面是一个简单的例子。有没有办法让MySQL执行一个查询,它将输出具有5个最高相邻值的值?我需要将查询调整为5,10,20等。

因此,如果你将ktim列中的每5个相邻单元格相加,那么最高的5将是7001.0-7003.5,因为它的总ktim为1997.53,并输出以下内容:

depth   ktim
7001.0  186.55
7001.5  577.98
7002.0  799.42
7002.5  334.15
7003.0   99.43

表格按深度排序,相邻性将始终根据深度计算。

1 个答案:

答案 0 :(得分:2)

真正的问题是获得最大值5和发生的位置。我看来,作为常规序列,深度增加0.5。如果你可以依赖于此,下面的查询将把第一个ktim值加起来直到当前值,然后返回最大值:

select t.*
from (select t.*,
             (select SUM(ktim) from t t2 where t2.depth between t.depth - 2.25 and t.depth
             ) as lastfivesum
      from t
     ) t
order by lastfivesum
limit 1

这将为您提供最后一行(示例中为7003.0)。如果您需要全部五个,您只需将其作为int:

连接回原始表
select t.*
from t join
     (select t.*
      from (select t.*,
                   (select SUM(ktim) from t t2 where t2.depth between t.depth - 2.25 and t.depth
                   ) as lastfivesum
            from t
           ) t
      order by lastfivesum
      limit 1
     ) tmax
     on t.depth bewteen tmax.depth - 2.25 and tmax.depth

我正在使用2.25而不是2来防止浮点数出现问题。