[英]PHP + Mysql - Get statistics for each day of the last 30 days
The table name is Users表名是用户
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
-------------------------------------------
How do I get how many new users i have received for each day of the last 30 days (using mysql or php or both).我如何获得过去 30 天内每天收到的新用户数量(使用 mysql 或 php 或两者)。 The results should look like this:结果应如下所示:
1-Sat 15
2-Sun 08
.
.
.
30-Fri 13
If the day has no records it shows 0.如果当天没有记录,则显示 0。
I tried this but i get stuck:我试过这个,但我卡住了:
select date_format(created_at,\'%a\') as day
from users
where datediff (now(),created_at) <=30
Thanks alot非常感谢
Here is a solution in 3 steps :这是一个分 3 个步骤的解决方案:
generate a list of the last 30 days (see detailed solution here : Select last 30 days in MySQL生成过去 30 天的列表(请参阅此处的详细解决方案: 在 MySQL 中选择过去 30 天
generate the number of registrations per day, with GROUP BY.使用 GROUP BY 生成每天的注册数量。 It is a key concept in SQL database, so I invite you to learn it if you use SQL regularly : SQL Group By它是SQL数据库中的一个关键概念,所以如果你经常使用SQL,我邀请你学习它: SQL Group By
Use a LEFT JOIN to keep all the dates in the calendar, and associate them to the number of registrations.使用 LEFT JOIN 将所有日期保留在日历中,并将它们与注册数量相关联。 If a day has no registration, the value will be NULL, so I used COALESCE
to return 0 in this case如果一天没有注册,则值为NULL,所以在这种情况下我使用COALESCE
返回0
Full query :完整查询:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.