从每个组发行中获取最短时间

时间:2016-01-26 01:35:53

标签: mysql time group-by min

我正在尝试获得每个组的最短时间,但我无法使其正常工作,min()函数似乎无法正常工作,只返回它为每个组找到的第一条记录。

我试过查询:

SELECT 
    *, 
    MIN(TIME_TO_SEC(IF(LENGTH(`time`)<6,CONCAT('00:',`time`),`time`))) 
FROM `test` 
GROUP BY `number`;

时间字段/列NEEDS采用Varchar格式!

预期结果:

1 - 59:09 - name3
2 - 48:02 - name2

http://sqlfiddle.com/#!9/972be/1

1 个答案:

答案 0 :(得分:0)

老兄,你有正确的方法只需要稍微调整一下。

select t1.`number`, t1.`name`,t1.`time` from
  (SELECT `number`,`name`,`time`,
          TIME_TO_SEC(IF(LENGTH(`time`)<6,CONCAT('00:',`time`),`time`)) as `min`
  FROM `test` GROUP BY `number`,`name`)t1
  left join
 (SELECT `number`,`name`,`time`,
         TIME_TO_SEC(IF(LENGTH(`time`)<6,CONCAT('00:',`time`),`time`)) as `min`
 FROM `test` GROUP BY `number`,`name`)t2
    on t1.`number`=t2.`number` and t1.`min` > t2.`min`
 where t2.`number` is null;

新的

 select t1.`map`,t1.`record`,t1.`name` from
(select `map`,`record`,`name`,
 replace(IF(LENGTH(`achieved`)<6,CONCAT('00:',`achieved`),`achieved`),':','') as mins
 from `records` where `record` = 'speedrun') t1
inner join
(select `map`,
min(replace(IF(LENGTH(`achieved`)<6,CONCAT('00:',`achieved`),`achieved`),':','')) as mins
from `records`
where `record` = 'speedrun' group by `map`) t2
on t1.`map` = t2.`map` and t1.mins = t2.mins