Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the average of a column in MySQL

I’m trying to find a way to calculate the average of a column (as a double, float or decimal). I’ve found the AVG() function in MySQL documentation but I can’t get it to work. Currently I’ve got the following code:

public double GetRating(string username)
        {
            double average;

            MySqlConnection databaseConnection = new MySqlConnection(connectionString);
            string sumQuery = "select sum('rating') from " + username;
            string countQuery = "SELECT COUNT(*) FROM " + username;
            using (MySqlCommand sumCommand = new MySqlCommand(sumQuery, databaseConnection))
            using (MySqlCommand countCommand = new MySqlCommand(countQuery, databaseConnection))

            try
            {
                databaseConnection.Open();
                
                double sum = (Double)sumCommand.ExecuteScalar();
                double columnLength = (Double)countCommand.ExecuteScalar();
                average = sum / columnLength;
                    return average;
             }

            finally
            {
                databaseConnection.Close();
            }

            return average;
            

        }

Now for some reason this does not work. It returns "Unable to cast object of type ‘System.Int64’ to type ‘System.Double’."

The stored data in the database is an int but i’m trying to cast them to double. Any suggestions or solutions? Once again; double, float or decimal are usable for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The built-in AVG function (an aggregate function) could be used like so:

select avg(rating) from table_name

Note that, like most aggregate functions, the average will exclude null values (the average of 1, 2, null is 1.5 instead of 1.0). Also, in MySQL the return datatype will be decimal if you’re averaging decimal or integer columns so use the appropriate C# datatype.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading