I have a column of numbers in a MySQL database, along with a timestamp column and other stuff. I want to know the average of all of the values within a set parameter (say, within the last week), and I also want the average of all of the values that are >= X during that same timeframe. So, if my X is 10, and my values are:
0 0 10 15 20
, then I want avg = 9
and avg2 = 15
. One way I can do this is run two separate queries, with and without WHERE val >= 10
, but I'd like to do it in just one query, if possible. Is there a way of doing this? I've looked at using a CASE, but I can't get the syntax right. Below is the query that I tried:
SELECT AVG(watts), AVG(CASE watts WHEN watts >= 10 THEN watts END CASE) FROM power WHERE meterID = 100 AND time >= '2010-07-29 00:00:00'
Edit: This is what I ended up with.
SELECT AVG(watts) AS avg1,
AVG(IF (watts >= 10, watts, NULL)) AS avg2
FROM power
WHERE meterID = 100 AND time >= '2010-07-30 00:00:00'