Lecture 8: SQL Select Part 2 and RA Flashcards
Explain Aggregate Functions
Often require to perform some form of summation or aggregation of data, similar to the totals at the bottom of a report
there are 5 aggregate functions, in SQL that we can use in SELECT command
each operates on a single column of a table and returns a single value
apart from count(*), each function eliminates nulls first and operates only on remaining non-null values
list the aggregate functions
COUNT SUM AVG MIN MAX
which two aggregate functions are only used on NUMERIC fields
SUM and AVG
List three aggregate functions that can apply to non-numeric and numeric fields
COUNT
MIN
MAX
What does count(*) do?
counts all rows of a table, regardless of whether nulls or duplicates values occur
What does distinct have an effect on?
no effect with : MIN/MAX
effect with
SUM/AVG
where are aggregate functions location?
can only be used in select list and in having clause
give an example of a meaningless aggreate function call
select staffNo, COUNT(salary)
from staff;
how to use count
SELECT COUNT(*) AS myCount FROM PropertyForRent WHERE rent > 350
how to use count and distinct
SELECT COUNT(DISTINCT propertyNo) AS myCount FROM viewing;
use of count and sum?
SELECT COUNT(staffNo) AS myCount,SUM(salary) AS mySum FROM Staff WHERE position = ‘Manager’
use of min, max and avg?
SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg FROM Staff;
How to use group by
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
Describe the having clause
having clause is designed for use with group by to restrict groups that appear in final result table
similar to where, but where filters individual rows whereas HAVING filters groups
column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function
Example of using having
select branchNo, count (staffNo) as mycount sum(salary) as mysum from staff group by branchNo having count (staffNo) > 1 order by branchoNo;