Chapter 3. Summarising results

Table of Contents
Totalling a field
Finding the maximum/minimum value
Counting doesn't give me the total number of records in a table
I want to know how many types of X are in the system
Defining your own aggregate function

Totalling a field

You want to calculate the total number of purchases per day or webpage hits per week.

Solution

Use SELECT a,b,sum(c) FROM t GROUP BY a,b; ref.

Discussion

You need to construct a SELECT query with a GROUP BY clause and apply a sum() function. So, to find the total number of orders we have per product in the system we can do:

SELECT p.pr_code, p.pr_desc, sum(o.ord_qty) AS quantity
FROM products p, orders o
WHERE p.pr_code=o.ord_product GROUP BY p.pr_code, p.pr_desc;
   

So why do we GROUP BY both the product-code and description, surely they match up? Well, they do, but if you return a field from a query it should either be mentioned in the GROUP BY or be subject to an aggregate function (such as sum). As an alternative we could have used:

SELECT p.pr_code, min(p.pr_desc), sum(o.ord_qty) AS quantity FROM products p, orders o WHERE p.pr_code=o.ord_product GROUP BY p.pr_code;
   

Which achieves the same since for any given pr_code we only have one pr_desc but probably isn't as clear.