Data Science Explorer

[Basic Grammar] SQL AVG() Function 본문

SQL

[Basic Grammar] SQL AVG() Function

grace21110 2023. 10. 15. 11:44
반응형

The AVG() function returns the average value of a numeric column.

 

  • Syntax 
SELECT AVG(column_name)
FROM table_name
WHERE condition;

 

Example 

Find the average price of all cups. 

SELECT AVG(Price)
FROM Cups;

** NULL is ignored**

 

  • Add a WHERE Clause 

You can specify conditions by using WHERE clause. 

 

Example 

Return the average price of sweaters in category 90:

SELECT AVG(Price) 
FROM Sweaters
WHERE CustomerID = 90;

 

  • Higher Than Average 

If you want to list records with a higher price than average, you can use the AVG() function in a sub query:

Example 

Return all the cups with a higher price than the average price:

SELECT * FROM Cups
WHERE price > (SELECT AVG (Price) FROM Cups);

 

Exercises 

1. Write an SQL query to retrieve all employees with a salary higher than the average salary in the "Employees" table.

SELECT * FROM Employees
WHERE salary > SELECT(AVG(salary) FROM Employees);

2. Select all orders with a total amount less than the average total amount in the "Orders" table.

SELECT * FROM Orders 
WHERE TotalAmount < SELECT (AVG(total amount) FROM Orders);

'SQL' 카테고리의 다른 글

[Basic Grammar] SQL IN Operator  (0) 2023.10.16
[Basic Grammar] SQL LIKE Operator  (0) 2023.10.16
[Basic Grammar] SQL Sum  (0) 2023.10.15
[Basic Grammar] SQL COUNT Function  (0) 2023.10.14
[Basic Grammar] SQL MIN() and MAX() Functions  (0) 2023.10.14