[英]Grouping rows based on "months" SQL
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.
因此,对于称为“不到 3 个月”的组,结果应显示 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.
我想也许我不应该使用 SUM,但不确定使用什么代替。 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
SELECT MonthGroup, SUM(count) as CountGroup
FROM
(Select
CASE
WHEN months<=2 THEN 'months_less_than_3'
WHEN months<=6 THEN 'months_3_6'
WHEN months<=12 THEN 'months_6_12'
WHEN months<=24 THEN 'months_12_24'
WHEN months>=20000 THEN 'Never'
WHEN months>=25 THEN'months_25_plus'
END AS MonthGroup, count
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
) t3
GROUP BY MonthGroup
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.