I have 3 tables:
Customers.
cust_id cust_name 1000000001 Village Toys 1000000002 Kids Place 1000000003 Fun4All 1000000004 Fun4All 1000000005 The Toy Store Orders.
cust_id order_num 1000000001 20005 1000000003 20006 1000000005 20008 1000000001 20009 OrderItems.
quantity item_price order_num 100 5.49 20005 100 10.99 20005 20 5.99 20006 10 8.99 20006 10 11.99 20006 5 4.99 20008 5 11.99 20008 10 3.49 20008 10 3.49 20008 10 3.49 20008 250 2.49 20009 250 2.49 20009 250 2.49 20009
And the following code:
SELECT cust_name, Orders.order_num, SUM(item_price * quantity) AS OrderTotal
FROM Customers
INNER JOIN Orders ON Customers.cust_id = Orders.cust_id
INNER JOIN OrderItems ON Orders.order_num = OrderItems.order_num
GROUP BY cust_name, Orders.order_num
ORDER BY cust_name, order_num;
The result is:
| cust_name | order_num | OrderTotal |
|---|---|---|
| Fun4All | 20006 | 329.60 |
| The Toy Store | 20008 | 189.60 |
| Village Toys | 20005 | 1648.00 |
| Village Toys | 20009 | 1867.50 |
If I remove cust_id from GROUP BY statement, I will get an error
The column "Customers.cust_name" is not allowed in the select list because it is not contained in either the aggregate function or the GROUP BY clause.
As I said I can't understand why GROUP BY is used with 2 columns. I can comprehend using only GROUP BY Orders.order_num because it will group OrderTotal by order_num. Also I don't know in which order columns are processed by GROUP BY. Is cust_name processed first or Orders.order_num?