我确定有人可以轻松回答这个问题,这会让我已经很穷的大脑受伤。
我有一个用户表:
created_date
id
user_type
我正在尝试在MYSQL中编写一个查询,该查询将从今天起计算30天,然后通过user_type回吐每天新增用户的数量(预计有些天可能为0)
想要一个类似于:
的结果date: | count(id[user_type = 1]) | count (id[user_type = 2])
2015-02-09 10 9
2015-02-08 0 10
2015-02-07 8 0
依旧......
谢谢!
答案 0 :(得分:0)
使用GROUP BY,并查看时间函数http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_day
... GROUP BY MONTH(created_date), DAY(created_date)
答案 1 :(得分:0)
这是一种可行的方法。 [http://sqlfiddle.com/#!2/090e19/24]
select
date_sub(date(now()), interval (d0.n0 + d1.n1 * 5) day),
count(case when user_type = 1 then 1 else null end),
count(case when user_type = 2 then 1 else null end)
from
(select 0 as n0 union all select 1 union all select 2 union all select 3 union all select 4) as d0
cross join
(select 0 as n1 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5) as d1
left outer join users as u on u.created_date = date_sub(date(now()), interval (d0.n0 + d1.n1 * 5) day)
and u.created_date >= date_sub(date(now()), interval 29 day)
group by date_sub(date(now()), interval (d0.n0 + d1.n1 * 5) day)
order by date_sub(date(now()), interval (d0.n0 + d1.n1 * 5) day) desc;