codesnout.com

SQL AGGREGATE FUNCTIONS

Google Ads

SQL Aggregate Functions


SQL Sample Code - SQL Aggregate Functions.


SELECT function_type(column_name)
FROM table_name;

See the SQL Samples section below for an explanation.


What do SQL Aggregate Functions do?

SQL aggregate functions return a value calculated from the values in a specified column. Such as adding a column’s values together or getting the average value of a given column.

The most commonly used Aggregate Functions are:

COUNT( ) - Returns the number of rows
AVG( ) - Returns the average value
SUM( ) - Returns the sum
FIRST( ) - Returns the first value
LAST( ) - Returns the last value
MAX( ) - Returns the largest value
MIN( ) - Returns the smallest value


SQL Sample 1 – SQL SUM() Function

In this SQL sample we will use the database table ‘tblCompany’.

Company_ID CompanyName Address Town Sales
1 SQL Sample 1 Sample St Hamburg 10000
2 SQL Code Land 2 Code Rd Hamburg 20000
3 Sample Code World 66 SQL St Curry 18000
4 SQL Reference Ltd 34 Reference St Pisa 17000

In this SQL sample we want to know the total SUM() for the Sales column in the tblCompany table.

Use the SELECT statement below:

SELECT SUM(Sales) AS Total_Sales FROM tblCompany;

The result will look like this:

Total_Sales
65000

Note: the AS operator is used to name the result column as ‘Total_Sales’. See the Alias section of this website to learn more about renaming database columns and tables.


SQL Sample 2 – SQL SUM() Function using GROUP BY.

In this SQL sample we will use the database table ‘tblCompany’.

Company_ID CompanyName Address Town Sales
1 SQL Sample 1 Sample St Hamburg 10000
2 SQL Code Land 2 Code Rd Hamburg 20000
3 Sample Code World 66 SQL St Curry 18000
4 SQL Reference Ltd 34 Reference St Pisa 17000

In this SQL sample we want to know the total SUM() for the Sales column in the tblCompany table for each Town.

Use the SELECT statement below:

SELECT Town, SUM(Sales) FROM tblCompany
GROUP BY Town;

The result will look like this:

Town SUM(Sales)
Hamburg 30000
Curry 18000
Pisa 17000

 


Related SQL Sample Code:


About Us | Privacy Policy | Contact Us | ©2010 Thunderousity Information Management Solutions | www.autosnout.com - Car Performance Statistics Website Utilising SQL | SQL Blog |

SQL Home | SQL Intro | SQL SELECT Statement | DISTINCT | WHERE | SQL Wildcards | AND OR | IN | BETWEEN | LIKE | ORDER BY | GROUP BY | TOP | ALIAS | DELETE | INSERT | UPDATE | CREATE DATABASE | CREATE TABLE | ALTER | INNER JOIN | FULL JOIN | LEFT JOIN | RIGHT JOIN | UNION | CONSTRAINTS | NOT NULL| Aggregate Functions | SUM | AVG | COUNT | MAX | MIN | FIRST | LAST | GROUP BY | HAVING | LIMIT | Microsoft Access Data Types | MySQL Data Types | SQL Server Data Types | ASCII HTML Reference Sheet |