Aggregate
Aggregate
Aggregate
FUNCTION
AGGREGATE FUNCTIONS
Aggregate functions are used to compute
against a "returned column of numeric data"
from your SELECT statement.
They basically summarize the results of a
particular column of selected data.
AGGREGATE FUNCTIONS
MIN
returns the smallest value in a given column
MAX
returns the largest value in a given column
SUM
returns the sum of the numeric values in a given column
AVG
returns the average value of a given column
COUNT
returns the total number of values in a given column
COUNT(*)
returns the number of rows in a table
EXAMPLES
Example 1:
SELECT AVG(salary)
FROM employee
This statement will return a single result
which contains the average value of
everything returned in the salary column
from the employee table.
EXAMPLES
Example 2:
SELECT AVG(salary)
FROM employee
WHERE title = 'Programmer'
This statement will return the average
salary for all employees whose title is equal
to 'Programmer'
EXAMPLES
Example 3:
SELECT Count(*)
FROM employees;
This particular statement is slightly
different from the other aggregate functions
since there isn't a column supplied to the
count function. This statement will return
the number of rows in the employees table.
GROUP BY CLAUSE
The GROUP BY clause will gather all of the
rows together that contain data in the
specified column(s) and will allow aggregate
functions to be performed on the one or
more columns.
GROUP BY CLAUSE
Syntax:
SELECT [aggregate function][column name]
FROM [table name]
GROUP BY [column name] / [column1,
column2, …..]
EXAMPLE 1:
Let's say you would like to retrieve a list of
the highest paid salaries in each dept:
SELECT max(salary), dept
FROM employee
GROUP BY dept
This statement will select the maximum
salary for the people in each unique
department. Basically, the salary for the
person who makes the most in each
department will be displayed. Their, salary
and their department will be returned.
HAVING CLAUSE
Defines the condition that is then applied to groups of rows
Syntax:
SELECT
FROM
GROUP BY
HAVING condition
Note:
condition contains an aggregate function or constants
HAVING EXAMPLES
Find book type and average price for that type. Only
show groups if the average price in that group is
greater than $12
SELECT type, avg(price) [Average Price]
FROM titles
GROUP BY type
HAVING avg(price) > 12
COMPUTE CLAUSE
Uses aggregate functions to calculate summary values
that appear as additional rows in the result of a
query
Syntax:
SELECT
FROM
WHERE
COMPUTE aggregate function
COMPUTE EXAMPLES
Display the title of the book whose price is
greater than 20. Compute the sum of the price
of the books.
SELECT title, price
FROM Titles
WHERE price >20
COMPUTE sum(price)
COMPUTE EXAMPLES
Display the employees
that were hired in 1992
and display the lowest
hired date.
SELECT fname, lname,
hire_date
FROM employee
WHERE hire_date
LIKE '%1992%'
COMPUTE min(hire_date)