Aggregate Functions
Examples of Aggregate Functions
Below are several examples of SQL aggregate functions. You can use these with a GROUP BY clause to aggregate rows based on the specified GROUP BY criterion. This can be a reporting tool.
COUNT
Returns the number of rows matching the query criteria.
SELECT COUNT(*) FROM Invoices WHERE Supplier = 'Bob'
COUNT(DISTINCT)
Returns the number of distinct, non-null field values matching the query criteria.
SELECT COUNT(DISTINCT InvoiceId) AS DistinctValues FROM Invoices WHERE Supplier = 'Bob'
AVG
Returns the average of the column values.
SELECT InvoiceId, AVG(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
MIN
Returns the minimum column value.
SELECT MIN(AnnualRevenue), InvoiceId FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
MAX
Returns the maximum column value.
SELECT InvoiceId, MAX(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
SUM
Returns the total sum of the column values.
SELECT SUM(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob'
COUNT
Returns the number of rows matching the query criteria.
SELECT COUNT(*) FROM Invoices WHERE Supplier = 'Bob'
COUNT(DISTINCT)
Returns the number of distinct, non-null field values matching the query criteria.
SELECT COUNT(DISTINCT InvoiceId) AS DistinctValues FROM Invoices WHERE Supplier = 'Bob'
AVG
Returns the average of the column values.
SELECT InvoiceId, AVG(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
MIN
Returns the minimum column value.
SELECT MIN(AnnualRevenue), InvoiceId FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
MAX
Returns the maximum column value.
SELECT InvoiceId, MAX(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob' GROUP BY InvoiceId
SUM
Returns the total sum of the column values.
SELECT SUM(AnnualRevenue) FROM Invoices WHERE Supplier = 'Bob'