简体   繁体   English

MySQL中的增量计数

[英]Incremental counts in mysql

I have a table "UserLogins" and when the user login into the system I will drop a record in the "UserLogins" table. 我有一个“ 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)

When I write the group by my results as follows 当我按我的结果写组时,如下

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

But I need an out put like as follows 但是我需要如下的输出

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

Your first count could simply be like this: 您的第一个数字可能只是这样:

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

while to count all users up to a given mount, I would use a Join: 在计算所有用户到给定的安装次数时,我将使用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')

on the subquery d I will return all last days of every month that has a record on the UserLogins table, then I will join all userlogin that logged up to the end of the month, and then I will do the count. 在子查询d上,我将返回在UserLogins表上有记录的每个月的最后几天,然后我将加入到月底登录的所有userlogin,然后进行计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM