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...//
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.
AVG() Syntax The SUM() function returns the total sum of a numeric column.
MySQL SUM() Function The SUM() function calculates the sum of a set of values.
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') .
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.
In Addition to what Reed said, you can also do the integer cast in SQL:
CAST(SUM(frequency) as INT) as sum_of_freq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With