Domanda

I have table in MySQL:

table

Question: How to group each row by 1 hour interval from range?

Wanted output:

range1 = 2014-01-28 00:00:00 to 2014-01-28 01:00:00
range2 = 2014-01-28 01:00:00 to 2014-01-28 02:00:00
range3 = 2014-01-28 02:00:00 to 2014-01-28 03:00:00
...

Array
(
    [range1] => Array
        (
            [id] => 1
            [time] => 2014-01-28 00:00:00
        )

    [range2] => Array
        (
            [id] => 2
            [time] => 2014-01-28 01:05:00
        )

    [range3] => Array
        (
            [id] => 3
            [time] => 2014-01-28 02:00:00
        )

)

My try:

PHP:

function get_data() {
    $start = date("Y-m-d 00:00:00");
    $end = date("Y-m-d H:i:s", strtotime('+1 DAY', strtotime($start)));
    $q = "
        SELECT *
        FROM table
        WHERE (time BETWEEN '" . $start . "' AND '" . $end . "')
    ";
    $select = mysqli_query($this->c, $q);
    while ($row = mysqli_fetch_assoc($select)) {
        $data[] = $row;
    }
    return $data;
}

Current output:

Array
(
    [0] => Array
        (
            [id] => 1
            [time] => 2014-01-28 00:00:00
        )

    [1] => Array
        (
            [id] => 2
            [time] => 2014-01-28 01:05:00
        )

    [2] => Array
        (
            [id] => 3
            [time] => 2014-01-28 02:00:00
        )

)
È stato utile?

Soluzione

SELECT * FROM table WHERE time BETWEEN '$start' AND '$end' GROUP BY DATE(time),DATEPART(hh,time)

This Query will Group By Hour of the same day , Where time between 2 values

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top