mysql中的增量计数

时间:2015-08-19 13:25:23

标签: mysql

我有一张桌子" UserLogins"当用户登录系统时,我将删除" UserLogins"表

Jan 10th (Users : 1,2,3,4)   // four records with Ids 1,2,3,4
Jan 20th (1,2,3,4,5,6)       // six records with Ids 1,2,3,4,5,6
Jan 30th (1,2)

Feb 10th (1,7)
Feb 20th (2,6,8)
Feb 25th (1,2,3,5)

Mar 10th (3,4)
Mar 20th (4,5,9)
Mar 30th (8,10,11)

Apr 10th (10,12)
Apr 20th (1,2,3,6,13, 14, 15)
Apr 30th (11,12,16)

当我按照以下结果编写小组时

Jan - 6
Feb - 7
Mar - 7
Apr - 11

但我需要一个如下的输出

Upto Jan - 6 //count of distinct users upto Jan
Upto Feb - 8 //count of distinct users upto Feb
Upto Mar - 11 //count of distinct users upto Mar
Upto Apr - 16 //count of distinct users upto Apr

1 个答案:

答案 0 :(得分:3)

你的第一个计数可能就是这样:

SELECT
  DATE_FORMAT(login_date, '%Y-%b') AS year_month,
  COUNT(DISTINCT user_id)
FROM
  UserLogins
GROUP BY
  DATE_FORMAT(login_date, '%Y-%b')

在计算所有用户到达给定挂载的同时,我会使用Join:

SELECT
  DATE_FORMAT(last_day, '%Y-%b') AS year_month,
  COUNT(DISTINCT user_id)
FROM
  (SELECT DISTINCT LAST_DAY(login_date) as last_day
   FROM UserLogins) d
  INNER JOIN
  UserLogins ON UserLogins.login_date<=last_day
GROUP BY
  DATE_FORMAT(last_day, '%Y-%b')

在子查询d上我将返回在UserLogins表上有记录的每个月的所有最后几天,然后我将加入记录到月末的所有用户登录,然后我将进行计数。 / p>