To complement a GROUP BY clause, use a HAVING clause to
apply one or more qualifying conditions to groups after they are formed.
The effect of the HAVING clause on groups is similar to the way the
WHERE clause qualifies individual rows. One advantage of using a HAVING
clause is that you can include aggregates in the search condition,
whereas you cannot include aggregates in the search condition of a
WHERE clause.
Each HAVING condition compares one column or
aggregate expression of the group with another aggregate expression
of the group or with a constant. You can use HAVING to place conditions
on both column values and aggregate values in the group list.
The
following query returns the average total price per item on all orders
that have more than two items. The HAVING clause tests each group
as it is formed and selects those that are composed of more than two
rows.
If you use a HAVING clause without a GROUP BY clause,
the HAVING condition applies to all rows that satisfy the search condition.
In other words, all rows that satisfy the search condition make up
a single group.
The following query, a modified version of Query, returns just one row, the
average of all total_price values in the table, as the result
shows.
If Query, like Query, had included the non-aggregate
column order_num in the Projection clause, you would have to
include a GROUP BY clause with that column in the group list. In addition,
if the condition in the HAVING clause was not satisfied, the output
would show the column heading and a message would indicate that no
rows were found.
The following query contains all the SELECT statement
clauses that you can use in the Informix® version
of interactive SQL (the INTO clause that names host variables is available
only in an SQL API).
The query joins the orders and items tables;
employs display labels, table aliases, and integers that are used
as column indicators; groups and orders the data; and puts the results
in a temporary table, as the result shows.