SQL Count, Avg, Sum
For example, let’s say we have a table called “sales” with the following columns:
id
(unique identifier for each sale)product
(name of the product sold)quantity
(number of items sold)price
(price per item)date
(date of the sale)
Now, let’s explore some common scenarios using the COUNT, AVG, and SUM functions.
- Count the total number of sales:
sql
SELECT COUNT(*) AS total_sales
FROM sales;
- Calculate the average price of all products sold:
sql
SELECT AVG(price) AS average_price
FROM sales;
- Calculate the total quantity of items sold:
sql
SELECT SUM(quantity) AS total_quantity
FROM sales;
- Calculate the total sales revenue:
sql
SELECT SUM(quantity * price) AS total_revenue
FROM sales;
- Count the number of sales for a specific product (e.g., “Product A”):
sql
SELECT COUNT(*) AS sales_count
FROM sales
WHERE product = 'Product A';
- Calculate the average price of a specific product (e.g., “Product B”):
sql
SELECT AVG(price) AS average_price
FROM sales
WHERE product = 'Product B';
These are just a few examples of how you can use the COUNT, AVG, and SUM functions in SQL queries. Let me know if you have any other specific requirements or if you need assistance with a different scenario!