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

I am writing a program in C # .NET I would like to collect the full frequency of the class (let each class have many words, and each word has its own frequency in the corresponding class)

So, I used the sum () function in mysql. But there is a mistake 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...// 
+6
source share
2 answers

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

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

If you need an integer, you can use Convert to get it regardless of the type of source:

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

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

+6
source

In addition to what Reid said, you can also make an integer expression in SQL:

 CAST(SUM(frequency) as INT) as sum_of_freq 
+3
source

Source: https://habr.com/ru/post/915741/


All Articles