加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

mysql – 用于计算每天注册用户数的SQL查询

发布时间:2020-12-11 23:47:44 所属栏目:MySql教程 来源:网络整理
导读:在尝试解决此问题时,我快要生气了: 在我的应用程序中,用户可以注册和删除他们自己.创建日期和删除日期作为时间戳保存在数据库中.我需要知道在一天中的每一天,当天有多少已注册和未删除的用户. 因此,如果我在2012-02-01上有10个现有用户,则在2012-02-03删除

在尝试解决此问题时,我快要生气了:

在我的应用程序中,用户可以注册和删除他们自己.创建日期和删除日期作为时间戳保存在数据库中.我需要知道在一天中的每一天,当天有多少已注册和未删除的用户.

因此,如果我在2012-02-01上有10个现有用户,则在2012-02-03删除该帐户的用户,2012-02-04中注册的3个用户和2012-02-06中删除的2个用户,以及查询从2012-02-01到2012-02-07的注册用户总数我想得到这样的结果:

day              total_users
2012-02-01       10
2012-02-02       10
2012-02-03       9
2012-02-04       12
2012-02-05       12
2012-02-06       10
2012-02-07       10

这就是我的简化用户表的样子:

user_id,user_name,created_at,deleted_at

获取一个特定日期的已注册和未删除用户的数量是没有问题的(在2012-02-01,这将在我的示例中得到10):

select application.application_id as application_id,count(user.user_id) as user_total
from application,user
where application.application_id = user.application_id
and date(user.created_at) <= '2012-02-01'
and ((date(user.deleted_at) > '2012-02-01') or (user.deleted_at is null))

谁知道如何创建一个具有我预期结果的查询(没有光标)?我的数据库是Debian上的MySQL 5.0.51.

提前致谢
马库斯 最佳答案 如果你有一个包含日期列表的表(称为日历),你可以使用如下查询:

select c.calendar_date,count(*) user_total
from calendar c
left join user u
       on date(u.created_at) <= c.calendar_date and 
          (date(u.deleted_at) > c.calendar_date or u.deleted_at is null)
group by c.calendar_date

如果您没有包含日期??列表的表,则可以使用以下查询模拟一个表:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) calendar_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where calendar_date between ? /*start of date range*/ and ? /*end of date range*/ 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读