Monday, January 28, 2013
0 comments

Using Max, Min and Sum aggreate functions in DataTable.Select()

10:42 AM
Using Max, Min and Sum aggreate functions in DataTable.Select() 


We can use all aggreate functions in DataTable.Select method, but the syntax we use in sql and DataTable select will be slightly different
Now we can see the syntax for using aggregate functions in sql and DataTable Select method

Lets try our aggreagate functions on Employee table. Employee table consists of EmployeeId, Name , MobileNumber, Age, Salary,Town, Address fields

Max in Sql
select max(Age) from employee
Max in DataTable
// Getting employee Employee
SqlCommand cmdEmp = new SqlCommand("Select * from Employee", con);
DataSet dataset1= new DataSet();
SqlDataAdapter daEmp = new SqlDataAdapter(cmdEmp);
daEmp .Fill(dataset1);
DataRow[] drAge = dataset1.Table[0].Select("Age = max(Age)");

Min in Sql
Select Min(Salary) from employee
Min in DataTable
DataRow[] drSalary = dataset1.Table[0].Select("Salary = max(Salary)");

Sum in Sql
Select Sum(Salary) from employee
Sum in DataTable
For Sum we need to use Compute method of the DataTable. The return type of compute method is object
object Salaries_Sum = dataset1.Table[0].Compute("sum(Salary )", "Salary > 0");
We need to pass two parameters for the Compute method.First parameter is String and Second parameter is Filter.
If we do not want to use Filter condition then we can leave second parameter blank.

Kumar now try with the following code to get sum
decimal totAmount=ds.Tables[0].Compunt("Sum(Amount)","");

0 comments:

 
Toggle Footer