Mysql Select语句基于小时,天,月,年

时间:2012-05-05 06:45:37

标签: mysql

我有一个值看起来像这样的表

id         time_stamp                    value    
1          2013-01-01 00:00:15           10
2          2013-01-01 01:00:15            5
3          2013-01-02 00:00:15           15
4          2013-01-02 01:00:15           20
5          2013-02-01 00:00:15           18
6          2013-02-01 01:00:15           15
7          2013-02-02 00:00:15           5
8          2013-02-02 01:00:15           17
9          2014-01-01 00:00:15           8
10         2014-01-01 01:00:15            5
11         2014-01-02 00:00:15           15
12         2014-01-02 01:00:15           30
13         2014-02-01 00:00:15           18
14         2014-02-01 01:00:15           15
15         2014-02-02 00:00:15           5
16         2014-02-02 01:00:15           17

从这张表中我想根据小时,天,月,年选择第一个记录值和最后一个记录值 例如,我根据

选择值

天:

id  time_stamp              start_value               end_value
1   2013-01-01              10                         5
2   2013-01-02              15                         20
3   2013-02-01              18                         15

and so on

Month:
id  time_stamp              start_value               end_value
1   2013 jan                10                         20
2   2013 feb                18                         17
3   2014 jan                8                          30
4   2014 feb                18                         17

Year:
id  time_stamp              start_value               end_value
1   2013                    10                         17
2   2014                    8                          17

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用mysql的聚合函数,如下面的

SELECT 
    t.id, 
    DATE_FORMAT(t.time_stamp, "%Y-%m-%d") AS time_stamp, 
    (SELECT `value` FROM table_name WHERE time_stamp BETWEEN DATE_FORMAT(t.time_stamp, "%Y-%m-%d 00:00:00") AND DATE_FORMAT(t.time_stamp, "%Y-%m-%d 23:59:59") ORDER BY id ASC LIMIT 1) AS start_value,
    (SELECT `value` FROM table_name WHERE time_stamp BETWEEN DATE_FORMAT(t.time_stamp, "%Y-%m-%d 00:00:00") AND DATE_FORMAT(t.time_stamp, "%Y-%m-%d 23:59:59") ORDER BY id DESC LIMIT 1) AS end_value
FROM table_name t 
GROUP BY DATE_FORMAT(t.time_stamp, "%Y-%m-%d")

我在查询中提供了额外的参数,以帮助您保持查询的灵活性:)