SQL Server > Query

Group by in SQL Server

How to return records in Group by column value in SQL Server?


To return records from the database based on group by a certain columns, we use GROUP BY keyword. This is generally done by those columns whose values are repeatative in nature into the database table.

To demonstrate this, we have used a view that was created as part of View examples discussed in the previous topic.

This view returns FirstName, LastName, Age from PersonalDetails table and NetSalary, PPFDeduction from Accounts table.

Now write following sql statement in the query window.

SELECT
              LastName,
              SUM(NetSalary) AS NetSalary,
              SUM(PPFDeduction) AS PPFDeduction
              FROM viewPersonalAccounts
GROUP BY LastName

This will sum NetSalary, PPFDeduction and give us the result grouped by LastName

Note

It is important to have the columns that are being used as Group by in the SELECT statement.

 Views: 7020 | Post Order: 51



Write for us






Hosting Recommendations