Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of SUM() in mysql?

Tags:

c#

mysql

I am writing a program in C#.NET I would like to gather the total frequency of a class (let imagine every class has many words and each word has its own frequency in the corresponding class)

So i used the sum() function in mysql. But there is an error saying that my cast is wrong.

 public void average_each_type()
        {
            MySqlDataReader result;
            int total_freq = 0;
            string type = "";

            command.CommandText = "select class_name ,SUM(frequency) as sum_of_freq from training_set group by class_name ";


                result = command.ExecuteReader();
                while (result.Read())
                {

                    total_freq = (int)result["sum_of_freq"]; //error happened here
                    type = result["class_name"].ToString();
                    //.....then so on...//
like image 895
qwr qwr Avatar asked May 14 '12 23:05

qwr qwr


People also ask

Does sum () return an int?

Return Value:Returns an integer indicating the total of all values of the iterable. The following example returns the sum of elements of the iterable.

What does sum return in SQL?

AVG() Syntax The SUM() function returns the total sum of a numeric column.

What does sum do in MySQL?

MySQL SUM() Function The SUM() function calculates the sum of a set of values.

How do I display the sum of two columns in MySQL?

Example: MySQL SUM() function using multiple columnsMySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .


2 Answers

SUM in MySql will return a decimal or double value, depending on the type within "frequency". From the documentation for SUM:

The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE). (Before MySQL 5.0.3, SUM() and AVG() return DOUBLE for all numeric arguments.)

If you want an integer, you can use Convert to get one no matter what the source type happens to be:

total_freq = Convert.ToInt32(result["sum_of_freq"]);

The advantage here is the Convert.ToInt32 will work no matter what type of value is returned from the database, provided it is a numeric type.

like image 176
Reed Copsey Avatar answered Sep 23 '22 22:09

Reed Copsey


In Addition to what Reed said, you can also do the integer cast in SQL:

CAST(SUM(frequency) as INT) as sum_of_freq
like image 45
rbu Avatar answered Sep 23 '22 22:09

rbu