簡體   English   中英

MySQL中的增量計數

[英]Incremental counts in 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

您的第一個數字可能只是這樣:

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表上有記錄的每個月的最后幾天,然后我將加入到月底登錄的所有userlogin,然后進行計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM