MySQL average of 2 columns using WHERE and GROUP BY year(), month()
Using MySQL. How can I find the average of the min_amount and max_amount columns while grouping by year(my_date) and month(my_date)?
Currently I'm planning on putting the sum of the columns in an array then average them using PHP.
Is there a way to get the average of the 2 grouped columns with an SQL query instead?
$sq开发者_高级运维l = "SELECT
SUM(min_amount) AS sum_min_amount,
SUM(max_amount) AS sum_max_amount,
my_date
FROM
table_1
WHERE
name = '$name'
AND
year(my_date) BETWEEN '$start_year' AND '$end_year'
AND
month(my_date) BETWEEN '$start_month' AND '$end_month'
GROUP BY
year(my_date), month(my_date)";
MySQL has an average function built in, so there should be no need to do this calculation on the PHP side of things, unless you have some hideous business requirements that can't be easily expressed in a query.
SELECT YEAR(my_date) AS year,
MONTH(my_date) AS month,
AVERAGE(min_amount) AS min_avg,
AVERAGE(max_amount) AS max_avg
FROM table_1
WHERE (my_date >= "$start_year-$start_month-01")
AND (my_date <= "$end_year-$end_month-31")
AND (name = $name)
GROUP BY year, month
You'd probably want to properly build the data strings outside of the query, and most definitely use a prepared statement for this, as the usual "you're wide open to SQL injection" attacks holds here.
精彩评论