MySQL的。如何选择每小时的最后日期

时间:2014-01-27 21:34:38

标签: mysql datetime

我在mysql数据库中有股票市场数据。我想找到每小时的收盘价。

我想出了这个问题:

SELECT MAX(date), price, FROM tradetable WHERE date BETWEEN '2014-01-25 23:00:00' AND '2014-01-28 12:59:59' GROUP BY hour(date) ORDER BY date;

但是我的结果没有按日期排序。它混乱了。小时和天数不合适。

我做错了什么?

返回的数据:

2014-01-27 02:59:59 --- 815.37000
2014-01-27 03:59:59 --- 813.00000
2014-01-27 04:59:59 --- 808.59998
2014-01-27 05:59:59 --- 812.07001
2014-01-27 06:59:59 --- 816.00000
2014-01-27 07:59:59 --- 825.84998
2014-01-27 08:59:59 --- 824.00000
2014-01-27 09:59:59 --- 825.50000
2014-01-27 10:59:59 --- 828.91998
2014-01-27 11:59:59 --- 820.00000
2014-01-27 12:59:59 --- 816.90002
2014-01-27 13:59:59 --- 821.20001
2014-01-26 14:59:59 --- 822.88000
2014-01-26 15:59:59 --- 819.00000
2014-01-26 16:59:59 --- 817.79999
2014-01-26 17:59:59 --- 817.78003
2014-01-26 18:59:59 --- 819.98999
2014-01-26 19:59:59 --- 816.66998
2014-01-26 20:59:59 --- 822.15997
2014-01-26 21:59:59 --- 819.52002
2014-01-26 22:59:59 --- 820.00000
2014-01-26 23:59:59 --- 816.00000
2014-01-27 00:59:59 --- 825.39001
2014-01-27 01:59:59 --- 821.90002

3 个答案:

答案 0 :(得分:1)

使用:

GROUP BY DATE(date), HOUR(date)

您将来自同一组中不同日子的时间进行组合。

答案 1 :(得分:0)

SELECT MAX(date), price, FROM tradetable WHERE date BETWEEN '2014-01-25 23:00:00' AND '2014-01-28 12:59:59' 
GROUP BY hour(date) ORDER BY date, time DESC

答案 2 :(得分:0)

您需要按日期和小时选择最大(日期)组,然后将该结果与贸易表联系起来以获取每小时的价格。

SELECT T1.date,T1.price
FROM tradetable T1
INNER JOIN
    (SELECT DATE(date) as tradedate,
            HOUR(date) as tradehour,
            MAX(date) as maxtime
     FROM tradetable
     WHERE date BETWEEN '2014-01-25 23:00:00' AND '2014-01-28 12:59:59'
     GROUP BY tradedate,tradehour
    )T2 
ON T1.date = T2.maxtime
ORDER BY T1.date