Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql avg on conditional

Tags:

mysql

average

is it possible to get the average value for a column, as well as the average value for the same column with a conditional? or simply to combine these two queries into one.

SELECT AVG( field ) from table

SELECT AVG ( field ) from table where col = some_val

If there isn't a simple way to combine them using native mysql functions, would a stored function be able to handle it, or a user defined function?

like image 218
Eric Pigeon Avatar asked Nov 15 '11 00:11

Eric Pigeon


People also ask

How does AVG work in MySQL?

MySQL AVG function is used to find out the average of a field in various records. You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.

How do I find the average of a group in MySQL?

Example: MySQL AVG() function with group byMySQL AVG() function retrieves the average value of a given expression for each group if it is used with group by option. The following statement will return the average number of pages for each group of 'pub_id' from book_mast table.

Does AVG function in SQL consider NULL?

AVG() function does not consider the NULL values during its calculation.


2 Answers

Taking advantage of the fact that null values are not included in aggregate functions, we can use a CASE statement to control the average, as in the following:

select avg(amt) as average,
       avg(case when col=some_val then amt else null end) as conditionalAverage
  from myTable;

Sample Demo: http://sqlize.com/2IXwbWD2Eb

like image 138
mellamokb Avatar answered Oct 18 '22 03:10

mellamokb


There is another way, not using case when

select 
   avg(amt) as average, 
   avg(if(col=some_val,amt,null)) as conditionalAverage
 from myTable
like image 38
kapiva Avatar answered Oct 18 '22 03:10

kapiva