我在试图解决这个问题时差点疯了:
在我的应用程序中,用户可以注册和删除自己。创建日期和删除日期作为时间戳保存在数据库中。我需要知道在一天中的每一天,当天有多少已注册和未删除的用户。
因此,如果我在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
获取一个特定日期的已注册和未删除用户的数量是没有问题的(这里是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。
提前致谢 马库斯
答案 0 :(得分: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
答案 1 :(得分: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*/