Поделиться через


How to: Specify Conditions for Groups

You can limit the groups that appear in a query by specifying a condition that applies to groups as a whole — a HAVING clause. After the data has been grouped and aggregated, the conditions in the HAVING clause are applied. Only the groups that meet the conditions appear in the query.

For example, you might want to see the average price of all books for each publisher in a titles table, but only if the average price exceeds $10.00. In that case, you could specify a HAVING clause with a condition such as AVG(price) > 10.

Note

In some instances, you might want to exclude individual rows from groups before applying a condition to groups as a whole. For details, see How to: Use HAVING and WHERE Clauses in the Same Query.

You can create complex conditions for a HAVING clause by using AND and OR to link conditions. For details about using AND and OR in search conditions, see How to: Specify Multiple Search Conditions for One Column.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings.

To specify a condition for a group

  1. Specify the groups for your query. For details, see How to: Group Rows in Query Results.

  2. If it is not already in the Criteria pane, add the column on which you want to base the condition. (Most often the condition involves a column that is already a group or summary column.) You cannot use a column that is not part of an aggregate function or of the GROUP BY clause.

  3. In the Filter column, specify the condition to apply to the group.

    The Query and View Designer automatically creates a HAVING clause in the statement in the SQL pane, such as in the following example:

    SELECT pub_id, AVG(price)
    FROM titles
    GROUP BY pub_id
    HAVING (AVG(price) > 10)
    
  4. Repeat steps 2 and 3 for each additional condition you want to specify.

See Also

Tasks

How to: Use HAVING and WHERE Clauses in the Same Query

Other Resources

Sorting and Grouping Query Results