我的表中有以下数据结构:
id member_from member_till
1 2014/03/01 2014/05/18
2 2014/01/09 2014/08/13
...
如何获取过去12个月中按月分组的活跃成员数?
例如:
...
2014/12/01,5
2015/01/01,12
作为未来的发展,是否可以将每个月的第一天和最后一天的平均值进行计数?
最佳答案
首先,您需要最近十二个月。然后外部加入成员,并计算月份在成员资格范围内的成员。
select
date_format(all_months.someday, '%Y %m') as mymonth,
count(membership.member_from) as members
from
(
select current_date as someday
union all
select date_add(current_date, interval -1 month)
union all
select date_add(current_date, interval -2 month)
union all
select date_add(current_date, interval -3 month)
union all
select date_add(current_date, interval -4 month)
union all
select date_add(current_date, interval -5 month)
union all
select date_add(current_date, interval -6 month)
union all
select date_add(current_date, interval -7 month)
union all
select date_add(current_date, interval -8 month)
union all
select date_add(current_date, interval -9 month)
union all
select date_add(current_date, interval -10 month)
union all
select date_add(current_date, interval -11 month)
) all_months
left join membership
on date_format(all_months.someday, '%Y %m')
between
date_format(membership.member_from, '%Y %m')
and
date_format(membership.member_till, '%Y %m')
group by date_format(all_months.someday, '%Y %m');
SQL提琴:http://www.sqlfiddle.com/#!2/6dc5a/10。
关于您将来的要求:您可以两次加入会员表,一次在一个月的第一次为会员,一次在该月的最后一次(失去那些仅在一个月中的某些天参加的人)。然后将两个计数相加并除以二。
关于mysql - 使用mysql从最近12个月获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28153733/