How to use Sum, Avg and Count in Select Statement - SQL Server / TSQL Tutorial Part 128

Scenario:

Let's say that you have dbo.Customer table with SaleAmount column and you are asked to write a query that should return you sum of SaleAmount, Average of SaleAmount and Count of all the records.

Solution:

You can use Aggregate functions such as Sum, Avg and count in TSQL to find the answer of your question.

Let's create dbo.Customer Table with sample data so we can use Sum, Avg and Count aggregate functions.



Create table dbo.Customer
 (Id int,
  FName VARCHAR(50),
  LName VARCHAR(50),
  CountryShortName CHAR(2),
  SaleAmount Int)
GO
--Insert Rows in dbo.Customer Table
insert into 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 run our query to find sum of SaleAmount, Avg of SaleAmount and Count of records.

SELECT Sum(saleamount) AS TotalSale, 
       Avg(saleamount) AS AvgSale, 
       Count(*)        AS SaleRecordCount 
FROM   dbo.customer 


How to use Sum, Avg and Count Aggregate Functions in SQL Server




2 comments:

  1. Students NCERT Economics Books in Class XI Provide in Your Collages, Every Year Government Collages free NCERT 11th Class Economics Book 2023 Distortion in Subject Wise new TextBooks 2023 for Students,But Any Problem Books not Available in Collage Don’t Worry,NCERT Class 11th Text books for Accountancy, Biology,Business Studies,Chemistry, Economics, English, Geography, Hindi, ,Mathematics,Physics,Political Science,Psychology, Sanskrit, Sociology,Statistics,Urdu etc. Students NCERT 11th Class Economics Text Book 2023 Available here to Download our Website at. Here we are Providing the Download Latest 11th class Edition NCERT books,you can Download NCERT 11th Class TextBooks 2023 for Hindi,English and Urdu Medium.

    ReplyDelete