Display the total sales of each salesperson from two tables, highest first
Expt. No.38
Page No.76
Join with GROUP BY and ORDER BY
Aim
To display the total sales amount of each salesperson by joining the SALESPERSON and SALES tables, grouping by name and sorting from the highest total.
Concepts used
Queries
USE shop;SELECT sname, SUM(amount) FROM salesperson, salesWHERE salesperson.spid = sales.spid GROUP BY sname ORDER BY SUM(amount) DESC;SELECT city, COUNT(*), SUM(amount) FROM salesperson, salesWHERE salesperson.spid = sales.spid GROUP BY city;
A marked line continues the line above it. In your file, write it on the same line.
Tables used
Table: salesperson
+------+-------+-------+ | spid | sname | city | +------+-------+-------+ | 1 | Ritu | Delhi | | 2 | Manoj | Pune | | 3 | Sneha | Delhi | +------+-------+-------+
Table: sales
+--------+------+--------+ | billno | spid | amount | +--------+------+--------+ | 101 | 1 | 12000 | | 102 | 2 | 8500 | | 103 | 1 | 9500 | | 104 | 3 | 15000 | | 105 | 2 | 4000 | | 106 | 3 | 6000 | | 107 | 1 | 3000 | +--------+------+--------+
Output
mysql> USE shop;
Database changed
mysql> SELECT sname, SUM(amount) FROM salesperson, sales
-> WHERE salesperson.spid = sales.spid GROUP BY sname ORDER BY SUM(amount) DESC;
+-------+-------------+
| sname | SUM(amount) |
+-------+-------------+
| Ritu | 24500 |
| Sneha | 21000 |
| Manoj | 12500 |
+-------+-------------+
3 rows in set
mysql> SELECT city, COUNT(*), SUM(amount) FROM salesperson, sales
-> WHERE salesperson.spid = sales.spid GROUP BY city;
+-------+----------+-------------+
| city | COUNT(*) | SUM(amount) |
+-------+----------+-------------+
| Delhi | 5 | 45500 |
| Pune | 2 | 12500 |
+-------+----------+-------------+
2 rows in set
✓ Printed by running this query set, not typed by hand.
Result
Ritu had the highest total (24500), then Sneha (21000) and Manoj (12500). Grouped by city, Delhi's salespersons made 5 sales worth 45500 and Pune's 2 sales worth 12500.
Viva voce: what the examiner may ask
01In what order are WHERE, GROUP BY and ORDER BY applied?
WHERE (join and filter rows), then GROUP BY, then ORDER BY on the grouped result.
02Why is the join condition needed?
Without it every sale would be paired with every salesperson and the totals would be wrong.
03Can you group by a column from the second table?
Yes; after the join, columns of both tables are available.
Variations for the lab test
- Display salespersons whose total is above 20000 using HAVING.
- Display the number of bills of each salesperson.
- Display the largest single sale of each salesperson.
! Common mistake Grouping by spid but displaying sname gives an error under ONLY_FULL_GROUP_BY; group by the column you display.