|
|
| · · · · · · · | |
pgAdmin 1.6 online documentation2.7. Aggregate Functions
Like most other relational database products,
PostgreSQL supports
aggregate functions.
An aggregate function computes a single result from multiple input rows.
For example, there are aggregates to compute the
As an example, we can find the highest low-temperature reading anywhere with SELECT max(temp_lo) FROM weather;
max ----- 46 (1 row)
If we wanted to know what city (or cities) that reading occurred in, we might try SELECT city FROM weather WHERE temp_lo = max(temp_lo); WRONG
but this will not work since the aggregate
SELECT city FROM weather
WHERE temp_lo = (SELECT max(temp_lo) FROM weather);
city --------------- San Francisco (1 row) This is OK because the subquery is an independent computation that computes its own aggregate separately from what is happening in the outer query.
Aggregates are also very useful in combination with SELECT city, max(temp_lo)
FROM weather
GROUP BY city;
city | max ---------------+----- Hayward | 37 San Francisco | 46 (2 rows)
which gives us one output row per city. Each aggregate result is
computed over the table rows matching that city.
We can filter these grouped
rows using SELECT city, max(temp_lo)
FROM weather
GROUP BY city
HAVING max(temp_lo) < 40;
city | max ---------+----- Hayward | 37 (1 row)
which gives us the same results for only the cities that have all
SELECT city, max(temp_lo)
FROM weather
WHERE city LIKE 'S%'(1)
GROUP BY city
HAVING max(temp_lo) < 40;
It is important to understand the interaction between aggregates and
SQL's In the previous example, we can apply the city name restriction in
|