Nesting groups with group by

You can list more than one column in the group by clause to nest groups. Once the sets are established with group by, the aggregates are applied. This statement finds the average price and the sum of book sales, grouped first by publisher identification number and then by type:

select pub_id, type, avg(price), sum(total_sales)
from titles
group by pub_id, type
pub_id  type
------  ------------  ------  ------- 
0736    business       2.99  18,722 
0736    psychology    11.48   9,564 
0877    UNDECIDED      NULL    NULL 
0877    mod_cook      11.49  24,278 
0877    psychology    21.59     375 
0877    trad_cook     15.96  19,566 
1389    business      17.31  12,066 
1389    popular_comp  21.48  12,875 
 
(8 rows affected)

You can nest many groups within groups, up to the maximum of 16 columns or expressions specified with group by.