i need help, i need to create report like this
x
age | total<br>
<= 13 | 10
14 | 0
15 | 5
16 | 2
| . .
the report is group by the age, but i can’t get when age under <= 13 to inside in 13 age, this is my query, it’s only work for same value, how to add value under 13 to be inside 13 age.
SELECT
za_hours.za_hour AS age,
IFNULL(COUNT(stonevoucherchild_claim_user_id), 0) AS total
FROM
(SELECT
13 AS za_hour
UNION
SELECT
14 AS za_hour
UNION
SELECT
15 AS za_hour
UNION
SELECT
16 AS za_hour
UNION
SELECT
17 AS za_hour
UNION
SELECT
18 AS za_hour
UNION
SELECT
19 AS za_hour
UNION
SELECT
20 AS za_hour
UNION
SELECT
21 AS za_hour
UNION
SELECT
22 AS za_hour
UNION
SELECT
23 AS za_hour
UNION
SELECT
24 AS za_hour
UNION
SELECT
25 AS za_hour
UNION
SELECT
26 AS za_hour
UNION
SELECT
27 AS za_hour
UNION
SELECT
28 AS za_hour
UNION
SELECT
29 AS za_hour
UNION
SELECT
30 AS za_hour) za_hours
LEFT JOIN mu_users
ON za_hours.za_hour = TIMESTAMPDIFF(YEAR, dob, CURDATE())
GROUP BY za_hours.za_hour
ORDER BY za_hours.za_hour;
please help me for this, and sorry for bad english
Advertisement
Answer
I would use a range comparison; this works by defining a start and end value in the union all
derived table; then you can use between
to put the users in groups. We can also provide a description for each range, that we will use in the outer query:
select n.info, count(u.dob) total
from (
select '<= 13' info, 0 start, 13 end
union all select '= 14', 14, 14
union all select '= 15', 15, 15
union all select '= 30', 30, 30
) n
left join mu_users u
on timestampdiff(year, u.dob, curdate()) between n.start and n.end
group by n.info, n.start, n.end
order by n.start