使用mysql从过去12个月获取数据

时间:2015-01-26 15:56:28

标签: mysql database count

我的表中有以下数据结构:

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

作为未来的发展,有可能将每个月的第一天和最后一天的平均值计算在内吗?

3 个答案:

答案 0 :(得分:0)

首先,你需要过去的十二个月。然后外部加入成员并计算月份在成员范围内的那些。

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

关于您未来的要求:您可以加入会员桌两次,一个月的第一个会员一次,一个月的最后一个会员一次(失去那些仅在一个月中的某些日子参加会议的人) 。然后添加两个计数并除以2。

答案 1 :(得分:0)

您可以尝试使用SQL Query:

SELECT `member_from`, count(id) FROM tbl_test WHERE `member_from` BETWEEN <From date> AND <To date> GROUP BY `member_from`;

答案 2 :(得分:0)

完成未来的要求:

SELECT
    d.ymonth,
    COUNT(m.member_from) total,
    COALESCE(SUM(d.fday BETWEEN m.member_from AND m.member_till), 0) total_fom,
    COALESCE(SUM(d.lday BETWEEN m.member_from AND m.member_till), 0) total_lom
FROM
    (
    SELECT
        CAST(@first_day := @first_day + INTERVAL 1 MONTH AS DATE) fday,
        LAST_DAY(@first_day) lday,
        DATE_FORMAT(@first_day, '%Y-%m') ymonth
    FROM
        information_schema.collations
    CROSS JOIN
        (SELECT @first_day := LAST_DAY(CURRENT_DATE) - INTERVAL 13 MONTH + INTERVAL 1 DAY) x
    LIMIT 12
    ) d
LEFT JOIN
    membership m
    ON d.lday >= m.member_from
    AND d.fday <= m.member_till
GROUP BY d.ymonth

子查询生成一个包含3列的虚拟查找表:

+ ---------- + ---------- + ------- +
| fday       | lday       | ymonth  |
+ ---------- + ---------- + ------- +
| 2014-02-01 | 2014-02-28 | 2014-02 |
|      \/    |      \/    |    \/   |
| 2015-01-01 | 2015-01-31 | 2015-01 |
+ ---------- + ---------- + ------- +

然后,成员资格表可以在重叠的member_from-member_till以及每个月的开始和结束时加入。