Subquery and JOIN2
Converting aggregate subqueries into Join functions.
DROP TABLE orders
CREATE TABLE orders( employee VARCHAR(40)), whn DATE(YYYY,MM,DD), totalitems INTEGER)); INSERT INTO orders VALUES ('Jim',(2006,10,10), 5); INSERT INTO orders VALUES ('Jim',(2006,10,11), 3); INSERT INTO orders VALUES ('Jim',(2006,10,12), 1); INSERT INTO orders VALUES ('Brian',(2006,10,10), 7);
SELECT customer, whn, totalitems FROM orders 01 WHERE 01.whn = ( SELECT MAX(whn) FROM orders 02 WHERE 01.customer = 02.customer)
To make this more efficient a HAVING clause can be used with a self join.
SELECT 01.customer, 01.whn, 01.totalitems FROM orders 01 JOIN orders 02 ON (01.customer = 02.customer) GROUP BY 01.customer, 01.whn, 01.totalitems HAVING 01.whn = MAX(02.whn)
Hack 10 Converting subqueries into joins
Hack 11 Converting aggregate subqueries into joins
Hack 16 Search for a String across columns
Hack 24 Multiply Across a Result Set
Hack 25.5 Splitting and combining columns
Hack 26 Include the rows your JOIN forgot
Hack 30 Calculate the maximum/minimum of two fields
Hack 33 Get values and subtotals in one shot
Hack 50 Combine tables containing different data
Hack 51/52 Display rows as columns
Hack 55 Import Someone Else's Data
Hack 62 Issue Queries Without Using a Table
Hack 63 Generate rows without tables
Hack 72 Extract a subset of the results
Hack 78 Break it down by Range
Hack 88 Test two values from a subquery