In this blog I am going to explain how can use group by
clause. I have an EMPLOYEE table and want to sum of salaries as per employee
name.
1. 1. Create Data Context Class:
First of all create a data context class that
has an EMPLOYEE table.
![empDataContext.PNG]()
1. 2. Create UI Design :
I use grid view to show employee data.
<asp:GridView ID="grdEmployee" runat="server"></asp:GridView>
3. Original Data :
Here I show whole data these contain by EMPLOYEE table.
SELECT * FROM EMPLOYEE
![originalempdata.PNG]()
4.
Group By in Sql Server:
Here I write a query in sql server's query
editor to get employee name and salary.
SELECT Name, SUM(SALARY) AS SALARY FROM EMPLOYEE GROUP BY Name
![sqlgroupby.PNG]()
1. 5. Group By in Linq To Sql
Here I create data context class object. This object
contains employee data.
private void
GetEmployee()
{
EmployeeOperationDataContext employee = new EmployeeOperationDataContext();
var salarySum = from
emp in employee.EMPLOYEEs
group emp by emp.Name into empg
select new { NAME = empg.Key, SALARY
= empg.Sum(x => x.SALARY)};
grdEmployee.DataSource = salarySum;
grdEmployee.DataBind();
}
Output:
![groupbylinq.PNG]()