1

私はこのような値のテーブルを持っています

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

これどうやってするの?

4

1 に答える 1

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")

クエリを柔軟に保つために、クエリに追加のパラメータを提供しました:)

于 2012-05-05T06:48:18.697 に答える