2012-02-16 63 views
5

我几乎惹毛了,而试图解决此问题:SQL查询来算注册用户每

在我的应用程序的用户可以注册并删除themselfes。创建日期和删除日期作为时间戳记在数据库中保存。我需要知道在一天中的每一天,当天有多少注册用户和未被删除的用户。

因此,如果我在2012-02-01上有10个现有用户,2012-02-03上删除了该帐户的一个用户,2012-02-04上注册了三个用户,2012-02- 06,和查询注册用户总数从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

这是没有问题的,以获得数Ò ˚F登记,不会被删除用户的某一天(这里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。

在此先感谢 马库斯

回答

2

如果你有一个日期在其列表(称为像日历)的表,你可以使用这样的查询:

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*/ 
+0

非常感谢,完美的作品!我只需要用t0,t1等替换每行中的“i”,我认为这是我的旧MySQL服务器的错。 – 2012-02-17 08:38:51

+0

@MarcusMuench:哎呀,我的错。我已更正查询 - 谢谢。 – 2012-02-17 10:25:02

2
SELECT date(user.created_at) as "creation_date", count(user.user_id) as "user_total" 
FROM application a 
INNER JOIN user u ON a.application_id = u.application_id 
WHERE date(user.created_at) <= '2012-02-01' 
AND ((date(user.deleted_at) > '2012-02-01') or (user.deleted_at is null)) 
GROUP BY date(user.created_at) 
ORDER BY date(user.created_at) ASC 
+0

+1。 @ user1214154,请注意,这将不会列出那天没有任何注册用户的日期,并将0作为计数。它只会输出表格中存在的天数 – talereader 2012-02-16 16:11:18

+0

这不会返回每天注册用户的数量 - 相反,它会返回每天在*上注册*的用户数量。考虑到问题中描述的示例数据,它将不会生成所需的输出 - 相反,它会在2012年2月1日之前生成多个用户和日期(总计最多添加10个用户),而2012年之后不会生成任何用户和日期 - 02-01。 – 2012-02-16 17:01:44