SQL SELECT COUNT, SUM, and AVG

SQL COUNT, SUM, AVG Functions

COUNT, SUM, and AVG are aggregate functions.

COUNT returns a count of the number of data values.

SUM returns the sum of the data values.

AVG returns the average of the data values.

Example

#

Problem: Get the total number of products.

SELECT COUNT(Id) AS 'Product Count'
  FROM Product

Syntax

COUNT syntax.

SELECT COUNT(column-name)
  FROM table-name

SUM syntax.

SELECT SUM(column-name)
  FROM table-name

AVG syntax.

SELECT AVG(column-name)
  FROM table-name

More Examples

SQL COUNT

CUSTOMER
Id
FirstName
LastName
City
Country
Phone
Problem: Get the total number of customers.
SELECT COUNT(Id) AS 'Customer Count'
  FROM Customer
Result:
Customer Count
91

SQL SUM

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: Calculate the total amount sold in 2013.
SELECT SUM(TotalAmount) AS 'Total Sales'
  FROM [Order]
 WHERE YEAR(OrderDate) = 2013
Result:
Total Sales
658388.75

SQL AVG

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: Get the average size of all orders.
SELECT AVG(TotalAmount) AS 'Avg Order'
  FROM [Order]
Result:
Avg Order
1631.877819

You may also like



Guides