我有一个 user_details 表,其中添加了每个登录名。我正在开发一个页面来查看每个 ID 以及过去 12 个月的每个月的登录计数,例如 >1 和 >10 等。
以下是我获取过去 30 天计数的查询:
SELECT count(*) FROM ( select intClientId from tbl_pi_userdetails where LoginTime >= NOW() - INTERVAL 30 DAY group by intClientId HAVING COUNT(intClientId) = 1)tbl_pi_userdetails
同样想要过去 14 个月的时间。
select
date_format(date_sub(now(), interval months_ago month), "%b %Y") as month,
count(intClientId) as count
from(
select
months_ago,
date(date_format(date_sub(now(), interval months_ago month),
"%Y-%m-01")) start_date,
date(date_format(date_sub(now(), interval months_ago-1 month),
"%Y-%m-01")) end_date
from (select 0 months_ago 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 union select 10 union select 11 union select
12 union select 13 order by months_ago) months_ago
) date_range left join tbl_pi_userdetails on LoginTime >= start_date and
LoginTime < end_date and
LoginTime <= now() group by intClientId, months_ago,
intClientId having count(intClientId) = 1;
最佳答案
预期结果
select month_year, count(*) from
(select DATE_FORMAT(LoginTime, '%Y-%m') as month_year, count(intClientId), intClientId
from tbl_pi_userdetails where
LoginTime >= now() - INTERVAL 15 MONTH
group by DATE_FORMAT(LoginTime, '%Y-%m'), intClientId having count(intClientId)> 1
order by DATE_FORMAT(LoginTime, '%Y-%m'), intClientId ) results
group by month_year
order by month_year desc;
fiddle :https://www.db-fiddle.com/f/9SLYF45hyWLQaokjDz2AAR/5
关于mysql - 用于获取 ID 计数值的 SQL 查询,其中 ID 计数 > 1 的最后 14 个跟踪月份按每月分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60037485/