Values and Subtotals
Get values and Subtotals in one shot.
<p>Table 1 shows the result without the subtotals and Table 2 shows the result with subtotals.
| whn | description | amount |
|---|---|---|
| 2006-11-01 | Wages | 50 |
| 2006-11-02 | Company Store | -10 |
| 2006-11-03 | Company Store | -10 |
| 2006-11-04 | Company Store | -10 |
| 2006-11-05 | Company Store | -10 |
| 2006-11-06 | Company Store | -10 |
| whn | description | amount |
|---|---|---|
| 2006-11-01 | Wages | 50 |
| 2006-11-02 | Company Store | -10 |
| 2006-11-03 | Company Store | -10 |
| 2006-11-04 | Company Store | -10 |
| 2006-11-05 | Company Store | -10 |
| 2006-11-06 | Company Store | -10 |
DROP TABLE serial
CREATE TABLE serial( item VARCHAR(20), serialnumber INTEGER, price INTEGER ); INSERT INTO serial VALUES ('Awl',1,10); INSERT INTO serial VALUES ('Awl',3,10); INSERT INTO serial VALUES ('Bowl',2,10); INSERT INTO serial VALUES ('Bowl',5,10); INSERT INTO serial VALUES ('Bowl',6,10); INSERT INTO serial VALUES ('Cowl',4,10);
In this example a UNION is used to make the query show the subtotal
results along with the price results and to ensure the subtotals come after
the price a COALESCE function is also used.
SELECT item, serialnumber, price FROM( SELECT item, serialnumber, price FROM serial UNION SELECT item, NULL, SUM(price) FROM serial GROUP BY item ) t ORDER BY item, COALESCE(serialnumber,1E9)
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