Results 1 to 3 of 3
  1. #1
    Join Date
    Nov 2011
    Posts
    1

    Unanswered: AVERAGE within time restraints, within intervals

    Hell0,

    I have a need to get the average values of a field within user defined time intervals, between user defined datetime's.

    Ex.

    I need the average of the temperature from 11-20-2011 01:00:00(startDate) to 11-22-2011 1:00:00(endDate), in 2 hour intervals.

    So the query would be averaging for 2 hours, then the next 2 hours until it reaches the endDate.

    So far I have figured out the problem using php and while loops but I would rather execute this with one query rather than potentially querying the database 1000 times.

    So far:

    SELECT date_time, AVG(input_calibrated)
    FROM inputs
    WHERE
    (date_time BETWEEN $startDate and $endDate)
    AND
    (chan_id = $chan_id)

    I guess what I really need is a way to get some sort of while loop within the query to run changing the the BETWEEN dates until the endDate is reached.

    And direction would be appreciated.

    Thank you

  2. #2
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    Id have a look at the GROUP BY sub clause, along with the MySQL date time functions
    rather than do this as a series of selects within a loop
    I'd rather be riding on the Tiger 800 or the Norton

  3. #3
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    You need to look at this problem slightly differently. For example, the periods that you are looking for are as follows:

    11-20-2011 01:00:00 until 11-22-2011 1:00:00 in two hour intervals

    If you convert the date to the format YYYYMMDD and the time to simply the hour HH then we can do something

    SELECT Date_format(date_time, '%Y%m%d'),
    Floor(( Date_format('%H') - 1 ) / 2),
    Avg(input_calibrated)
    FROM inputs
    WHERE ( date_time BETWEEN $startdate AND $enddate )
    AND ( chan_id = $chan_id )
    GROUP BY Date_format(date_time, '%Y%m%d'),
    Floor(( Date_format('%H') - 1 ) / 2);

    Basically we subtract 1 from the hour and then divide by 2. So 01:00 will return FLOOR((1-1)/2) or 0, 02:00 will return FLOOR((2-1)/2) or 0, 03:00 will return 1 and so on. As we are grouping by the date and the interval you will have all the results returned for every two hour period between the intervals selected.
    Ronan Cashell
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •