mysql - 用于获取 ID 计数值的 SQL 查询,其中 ID 计数 > 1 的最后 14 个跟踪月份按每月分组

标签 mysql grouping

我有一个 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;

我的表看起来像这样,具有不同的 ID 和登录时间。 enter image description here

预期结果: enter image description here

最佳答案

预期结果

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/

相关文章:

mysql - 使用 CakeDC 搜索插件链接两个模型

mysql - 如何通过另一个表检查 "duplicates"?

Silverlight:Datagrid 类似于 ItemsControl 中的分组

postgresql - Postgres 如何实现 CUBE-、ROLLUP- 和 GROUPING SETS 运算符

在 R 中逐行删除重复值

mysql - 创建 SUM 表的触发器并插入到另一个表中

php - 更新为 NULL Mysql

xslt - 在 for-each-group 之后添加预告片总金额

algorithm - 如何将点分组在同一条曲线 "row"中?

MySQL 将一对多组合成一行