Question

i test alot today and googled like hell but dint get it to work. i want to query my db and want to get back max (highest value) in a week day hour etc.

Table contains

date       time     id  val1    val2    val3
2014-02-11 09:20:05 1   0.5      0.1    0.4
2014-02-11 09:20:10 2   0.4      0.2    0.14
2014-02-11 09:20:15 3   0.7      0.4    1.7
2014-02-11 09:20:20 4   0.4      0.4    4.7
2014-02-11 09:20:25 5   0.6      0.8    8.7
2014-02-11 09:20:30 6   5.4      0.1    8.7
2014-02-11 09:20:35 7   0.9      0.8    1.5
2014-02-11 09:20:40 8   0.1      0.6    8.3
2014-02-11 09:20:45 9   0.5      0.8    4.7
2014-02-11 09:20:50 10   0.8      0.9    7.7
2014-03-24  14:30:15 656931 0.4     0.6    2.4 <- last row

Know i want to get the Max val1 of every min

date       time     maxval1
2014-02-11 09:21 5.4 
2014-02-11 09:22 1.1 
2014-02-11 09:23 3.9 
2014-02-11 09:24 4.8 
2014-02-11 09:25 7.7 
2014-02-11 09:26 8.5 
2014-02-11 09:27 9.4... 

next i want to get he max val1 of every hour

date       time     maxval1
2014-02-11 09:00 5.4 
2014-02-11 10:00 1.1 
2014-02-11 11:00 3.9 
2014-02-11 12:00 4.8 
2014-02-11 13:00 7.7 
2014-02-11 14:00 8.5 
2014-02-11 15:00 9.4...

day

2014-02-11 1.2
2014-02-12 4.4
2014-02-13 9.9
2014-02-14 6.4
2014-02-15 9.6
2014-02-16 4.7
2014-02-17 5.4...

month

2014-02 9.9
2014-03 4.4
2014-04 9.9
2014-05 9.4
2014-06 7.6
2014-07 6.7
2014-08 3.4...

best if the outputtime was unixtime (for charting)

i have edited the question for you

Was it helpful?

Solution

You asked for maximum values "a week day hour etc." I fear that's kind of a vague specification.

You can get the max value for each day like so:

 SELECT date AS day,
        MAX(value1) AS maxval1
   FROM testdb
  GROUP BY date
  ORDER BY date

If you had a DATETIME column instead of separate date and time columns, this whole thing would be a lot easier and far faster.

You can get the max value for each hour like so:

 SELECT DATE_FORMAT(STR_TO_DATE(CONCAT(date,' ',time)), '%Y-%m-&d %H:00:00') AS hour,
        MAX(value1) AS maxval1
   FROM testdb
  GROUP BY DATE_FORMAT(STR_TO_DATE(CONCAT(date,' ',time)), '%Y-%m-&d %H:00:00')
  ORDER BY DATE_FORMAT(STR_TO_DATE(CONCAT(date,' ',time)), '%Y-%m-&d %H:00:00')

In this query the expression

DATE_FORMAT(STR_TO_DATE(CONCAT(date,' ',time)), '%Y-%m-&d %H:00:00')

takes the date/time combination and truncates it to the top of the most recent hour. For example, it changes '2013-04-01 08:35:20' to '2013-04-01 08:00:00"

Similar expressions work to truncate timestamps to other things, like the week (the previous Sunday at midnight) or the nearest quarter hour. Here's some background. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top