聚合操作符 Aggregate Operators
Sailors
sid | sname | rating | age |
---|
22 | Dustin | 7 | 45.0 | 29 | Brutus | 1 | 33.0 | 31 | Lubber | 8 | 55.5 | 32 | Andy | 8 | 25.5 | 58 | Rusty | 10 | 35.0 | 64 | Horatio | 7 | 35.0 |
Reserves
sid | bid | day |
---|
22 | 101 | 10/10/04 | 22 | 102 | 10/10/04 | 22 | 103 | 10/08/04 | 22 | 104 | 10/07/04 | 31 | 102 | 11/10/04 |
Boats
bid | bname | Color |
---|
101 | Interlake | blue | 102 | Interlake | red | 103 | Clipper | green | 104 | Marine | red |
- 注意当使用Aggregate Operators时,target list(select 语句)中只能有aggregate attribute,不能有其他的attribute, 除非使用GROUP BY或者HAVING
COUNT(A)
Count the number of sailors
SELECT COUNT (*)
FROM Sailors S;
Count the number of different sailors
SELECT COUNT (DISTINCT S.sname)
FROM Sailors S
SUM(A)
Find the sum of ages of all sailors with a rating of 10
SELECT SUM (S.age)
FROM Sailors S
WHERE S.rating=10;
AVG(A)
Find the average age of all sailors with rating 10
SELECT AVG (S.age)
FROM Sailors S
WHERE S.rating=10
MAX(A), MIN(A)
Find the name and age of the oldest sailor
SELECT S.sname, MAX(S.age)
FROM Sailors S;
SELECT S.sname, S.age
FROM Sailors S
WHERE S.age = ( SELECT MAX(S2.age)
FROM Sailors S2 );
SELECT S.sname, S.age
FROM Sailors S
WHERE ROWNUM <= 1
ORDER BY S.age DESC;
GROUP BY and HAVING
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
Example: 查找总访问量大于 200 的网站
SELECT Websites.name, Websites.url, SUM(access_log.count) AS nums FROM (access_log
INNER JOIN Websites
ON access_log.site_id=Websites.id)
GROUP BY Websites.name
HAVING SUM(access_log.count) > 200;
Example: 将相同的business_id分组 HAVING COUNT(business_id) = 2 计算每个分组中相同的business_id的数量,挑选count = 2的business_id
SELECT DISTINCT business_id
FROM BUSINESS_MAIN_CATEGORIES t
WHERE t.main_category in ('Convenience Stores', 'Dentists')
GROUP BY business_id
HAVING COUNT(business_id) = 2
|