我需要从我的数据库中每小时选择第一个值。但我不知道如何在GROUP BY语句上颠倒顺序。 如何重写我的查询(现在它以小时为单位选择最后值)?
SELECT HOUR(`time`) as hour, mytable.*
FROM mytable
WHERE DATE(`time`) ="2015-09-12" GROUP BY HOUR(`time`) ORDER BY `time` ASC;
答案 0 :(得分:1)
这个查询给了我预期的结果:
SELECT HOUR(`time`) as hour, sortedTable.* FROM
(SELECT electrolysis.* FROM electrolysis
WHERE DATE(`time`)='2015-09-12' ORDER BY `time`) as sortedTable
GROUP BY HOUR(`time`);
答案 1 :(得分:0)
您只需在子查询中选择MIN HOUR,尝试使用查询:
SELECT * from mytable WHERE `time` IN (
SELECT MIN(HOUR(`time`)) as `hour`
FROM mytable
WHERE DATE(`time`) ="2015-09-12"
GROUP BY HOUR(`time`) ) ORDER BY `time` ASC;
答案 2 :(得分:0)
您可以这样做: -
SELECT sub0.min_time,
mytable.*
FROM mytable
INNER JOIN
(
SELECT MIN(`time`) AS min_time
FROM mytable
GROUP BY HOUR(`time`)
) sub0
ON mytable.`time` = sub0.min_time
WHERE DATE(`time`) ="2015-09-12"
ORDER BY `time` ASC
这是使用子查询来获取每小时的最小时间。然后在最短的时间内将其与主表连接起来以获得此时的记录。
请注意,如果有多个记录与一小时的最小记录共享同一时间,则此处存在潜在问题。有很多方法可以解决这个问题,但这取决于你的数据(例如,如果你有一个唯一的id字段总是随时间升序那么你可以选择每小时的最小id并加入基于那)
答案 3 :(得分:0)
您可以使用以下查询,这是更优化的,只需确保时间字段应编入索引。
SELECT HOUR(m.time), m.*
FROM mytable AS m
JOIN
(
SELECT MIN(`time`) AS tm
FROM mytable
WHERE `time` >= '2015-09-12 00:00:00' AND `time` <= '2015-09-12 23:59:59'
GROUP BY HOUR(`time`)
) AS a ON m.time=a.tm
GROUP BY HOUR(m.time)
ORDER BY m.time;