Scenario:
You are working as SQL Server Developer. You have a dbo.Customer table which has CountryShortName and SaleAmount. You are asked to write a query that should return Sum of SaleAmount , count of records by CountryShortName.
Solution:
Group by clause is often used with aggregate functions such as Sum, Avg,Count,Max,Min to group the result set by column/s.
Let's create our sample table with some data and write our query with Group by to answer our question.
Createtable dbo.Customer
(Id int,
FName VARCHAR(50),
LName VARCHAR(50),
CountryShortName CHAR(2),
SaleAmount Int)
GO
--Insert Rows in dbo.Customer Table
insertinto dbo.Customer
Values (
1,'Raza','M','PK',10),
(2,'Rita','John','US',12),
(3,'Sukhi','Singh',Null,25),
(4,'James','Smith','CA',60),
(5,'Robert','Ladson','US',54),
(6,'Alice','John','US',87),
(6,'John',Null,'US',Null)
Let's write our query by using Sum, Count and Group by Clause
SELECTSum(saleamount) AS TotalSaleByCountry,
Count(*) AS RecordCountByCountry,
countryshortname
FROM dbo.customer
GROUPBY countryshortname
How to use Group by Clause in SQL Server
You can also use multiple columns in group by clause. think about if our table would have states and you would like to group by CountryShortName and State, You would simple include State in query as shown below.
SELECTSum(saleamount) AS TotalSaleByCountry,
Count(*) AS RecordCountByCountry,
countryshortname,
[State]
FROM dbo.customer
GROUPBY countryshortname,[State]