I have a working query that produces the table shown below.
The query:
Select * from (
SELECT months, count(user_id) as count
from
(
select u.user_id, u.region_id, u.latest_login, year(u.latest_login),
period_diff(date_format(now(), '%Y%m'),date_format(u.latest_login, '%Y%m')) as months
from users u
where u.date_ended = 0000-00-00
AND country_id = 1
AND intRoleId = 3
)
t1
group by months
)
t2
The table:
I want to group rows based on the "months" number, and have the counts merged. So for a group called "less than 3 months" the result should show 140.
Below is the query that I've tried but the results are not correct. I think maybe I shouldn't be using SUM, but not sure what to use instead. Any suggestions on how to get the result I want?
Select months, count,
sum(months<=2) as months_less_than_3_,
sum(months>=3) as months_3_6,
sum(months>=6) as months_6_12,
sum(months>=12) as months_12_24,
sum(months>=24) as months_25_plus,
sum(months>=20000) as Never
from (
SELECT months, count(user_id) as count
from
(
select u.user_id, u.region_id, u.latest_login, year(u.latest_login),
period_diff(date_format(now(), '%Y%m'),date_format(u.latest_login, '%Y%m')) as months
from users u
where u.date_ended = 0000-00-00
AND country_id = 1
AND intRoleId = 3
)
t1
group by months
)
t2