AVG() function
The AVG() function calculates the average value of a column in a table or in a set of rows, depending on how to used. One important thing on here that only numeric values can be passed to the AVG() function. We can use CONVERT() to return the numeric value of a number stored as text.
Summary:
SELECT AVG(Column_name)
FROM table_name
Example:
Suppose we have a table ‘tbl_employee’
Table name: tbl_Employee
Employee Id | EmpName | Salary | Department |
1 | Ankur | 1200 | Sales |
2 | David | 3400 | Sales |
3 | John | 1500 | HR |
4 | James | 1200 | Production |
5 | Mohan | 4500 | Production |
6 | Ram | 2300 | HR |
- Calculate the average value of a salary of employee .
SELECT AVG(salary) FROM tbl_Employee
And output will look like this:
2350 |
2. Calculate the average salary in ‘HR’ department:
SELECT AVG(salary) FROM tbl_Employee WHERE Department=’HR’
And output will look like this:
1900 |
COUNT() function
COUNT() function in SQL Server is very common function that returns the count of the rows in the query that match a particular WHERE clause. We need to pass the asterisk to the count as COUNT(*) function to get a row count from a query.
Summary:
SELECT COUNT(*)
FROM table_name
Example:
Suppose we have a table ‘tbl_employee’
Table name: tbl_Employee
Employee Id | EmpName | Salary | Department |
1 | Ankur | 1200 | Sales |
2 | David | 3400 | Sales |
3 | John | 1500 | HR |
4 | James | 1200 | Production |
5 | Mohan | 4500 | Production |
6 | Ram | 2300 | HR |
- Get the total numbers of the records in the table:
SELECT COUNT(*) FROM tbl_Employee
And output will look like this:
6 |
2. Get the total numbers of employees in ‘HR’ department:
SELECT COUNT(*) FROM tbl_Employee WHERE Department=’HR’
And output will look like this:
2 |