表名称为用户
ID | name | created_at
------------------------------------------
1 | John | 2018-11-08 14:06:05
2 | Adam | 2018-12-12 10:06:05
3 | Peter | 2019-01-08 17:16:05
-------------------------------------------
我如何获得最近30天内每天(使用mysql或php或两者兼有)有多少新用户。结果应如下所示:
1-Sat 15
2-Sun 08
.
.
.
30-Fri 13
如果当天没有记录,则显示0。
我尝试过但是被卡住了:
select date_format(created_at,\'%a\') as day
from users
where datediff (now(),created_at) <=30
非常感谢
答案 0 :(得分:0)
这是3个步骤的解决方案:
生成最近30天的列表(请在此处查看详细解决方案:Select last 30 days in MySQL
使用GROUP BY每天生成注册数量。这是SQL数据库中的关键概念,因此如果您定期使用SQL,我邀请您学习它:SQL Group By
使用LEFT JOIN将所有日期保留在日历中,并将它们与注册数量相关联。如果一天没有注册,该值将为NULL,因此在这种情况下,我使用COALESCE
返回0
完整查询:
SELECT calendar.day, COALESCE(daily_registrations.nb_created, 0)
FROM
(
SELECT DATE_FORMAT(m1, '%a %d %M') AS day
FROM (
SELECT SUBDATE( NOW() , INTERVAL 30 DAY) + INTERVAL m DAY AS m1
FROM (
select @rownum:=@rownum+1 as m from
(select 1 union select 2 union select 3 union select 4) t1,
(select 1 union select 2 union select 3 union select 4) t2,
(select 1 union select 2 union select 3 union select 4) t3,
(select 1 union select 2 union select 3 union select 4) t4,
(select @rownum:=-1) t0
) d1
) d2
WHERE m1 <= now()
ORDER BY m1
) calendar
LEFT JOIN
(
SELECT date_format(created_at,'%a %d %M') AS day, COUNT(*) AS nb_created
FROM users
WHERE datediff (now(),created_at) <=30
GROUP BY day
)
daily_registrations
ON calendar.day = daily_registrations.day