Test subquery
Here you are shown how to test two values from your subquery
to ensure that it has run correctly.
Customer | Item | Price |
---|---|---|
Brian | Table | 100 |
Robert | Chair | 20 |
Robert | Carpet | 200 |
Janette | Statue | 300 |
Customer | Item | Price |
---|---|---|
Brian | Table | 100 |
Robert | Carpet | 200 |
Janette | Statue | 300 |
DROP TABLE custItem;
CREATE TABLE custItem (
Customer VARCHAR(20),
Item VARCHAR(20),
Price INT );
INSERT INTO custItem VALUES ('Brian','Table',100);
INSERT INTO custItem VALUES ('Robert','Chair',20);
INSERT INTO custItem VALUES ('Robert','Carpet',200);
INSERT INTO custItem VALUES ('Janette','Statue',300);
Suppose you have a table of customers and their orders, as shown in Table 1 and you want to produce a list of every customer and their biggest order, as shown in Table 2. This is easy enough to do with:
SELECT Customer, MAX(price) FROM custItem GROUP BY Customer
But by testing the results you can obtain the item that was purchased as well.
SELECT x.Customer, x.Item, x.Price
FROM custItem x JOIN (
SELECT Customer, MAX(price) AS Price
FROM custItem
GROUP BY Customer) y
ON (x.Customer = y.Customer AND x.Price = y.Price)
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