Range
Here you are shown how to break your query down by range.
DROP TABLE population;
CREATE TABLE population (
id INT,
age INT,
spend INT );
INSERT INTO population VALUES (1,34,100);
INSERT INTO population VALUES (2,31,110);
INSERT INTO population VALUES (3,24,140);
INSERT INTO population VALUES (4,35,130);
INSERT INTO population VALUES (5,39,120);
In this example if you want to see how much different age groups spend
then you will have to group the individuals in specific ranges.
First you use ROUND
to group together the different age groups.
You then use the AVG
function to find the average they spend.
Finally you use a CONCAT
function to make the age ranges more clear.
SELECT (low-5) || '-' || (low+4) AS the_range,
avgSpend
FROM (SELECT ROUND(age,-1) AS low,
AVG(spend) AS avgSpend
FROM population
GROUP BY ROUND(age,-1)) t
SELECT CONCAT(low-5,'-' ,low+4) AS the_range,
avgSpend
FROM (SELECT ROUND(age,-1) AS low,
AVG(spend) AS avgSpend
FROM population
GROUP BY ROUND(age,-1)) t
SELECT STR(low-5) + '-' + STR(low+4) AS the_range,
avgSpend
FROM (SELECT ROUND(age,-1) AS low,
AVG(spend) AS avgSpend
FROM population
GROUP BY ROUND(age,-1)) t
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