The GROUP BY and HAVING Clauses
Purpose: To apply aggregate operators to each of several groups of records.
Example: Find the age of the
youngest sailor for each rating level.
Should you repeat the following statements?
SELECT MIN (S.age)
FROM Sailors S
WHERE S.rating = i; The i could be 1, 2, ..., 10.
Solution:
SELECT S2.rating, MIN(S2.age)
FROM Sailors S2
GROUP BY S2.rating;
Example: Find the
age of the youngest sailor who is eligible to vote
(i.e. is at least 18 years old) for each rating with at least two such sailors.
SELECT
S.rating,
MIN (S.age) AS minage
FROM
Sailors S
WHERE
S.age >= 18
GROUP BY
S.rating
HAVING
COUNT (*) > 1 ;
