我目前正在将过去12个月中的月份/年份组合的单个查询中的特定月份或之前创建的用户分配计算在内。但是,事实证明这些方法比我想的要慢,我想看看是否有一种方法可以将所有这些查询组合为一个。
这是从Ruby on Rails(5.0)应用程序通过连接到MySQL数据库(5.6.10)的ActiveRecord模型运行的。
此ActiveRecord查询
User.joins(:child_classrooms).where('assignments.created_at <= ?', DateTime.new(month_year[0], month_year[1]).end_of_month).count('DISTINCT users.id')
产生此mysql查询
SELECT COUNT(DISTINCT users.id)
FROM `users` INNER JOIN `assignments` ON `assignments`.`user_id` = `users`.`id` AND `assignments`.`role_id` = 3 AND `assignments`.`assignable_type` = 'Student'
INNER JOIN `students` ON `students`.`id` = `assignments`.`assignable_id`
INNER JOIN `classrooms_students` ON `classrooms_students`.`student_id` = `students`.`id`
INNER JOIN `classrooms` ON `classrooms`.`id` = `classrooms_students`.`classroom_id`
WHERE (assignments.created_at <= '2019-04-30 23:59:59')
上面的查询产生了十二次(过去十二个月中的每个月一次,更改where子句时间戳),而我想让一个查询返回按年和月分组的相同数据,计数为{{1 }}分组的年份和月份。
我熟悉如何按年和月分组,但令我感到困惑的是如何仅计算时间戳记创建的在年和月分组之前或之前的行。
答案 0 :(得分:0)
您还需要选择年份和月份,因此每行都需要一行。然后,您可以按thos列进行分组:
SELECT year(assignments.created_at),month(assignments.created_at),COUNT(DISTINCT users.id)
FROM `users` INNER JOIN `assignments` ON `assignments`.`user_id` = `users`.`id` AND `assignments`.`role_id` = 3 AND `assignments`.`assignable_type` = 'Student'
INNER JOIN `students` ON `students`.`id` = `assignments`.`assignable_id`
INNER JOIN `classrooms_students` ON `classrooms_students`.`student_id` = `students`.`id`
INNER JOIN `classrooms` ON `classrooms`.`id` = `classrooms_students`.`classroom_id`
WHERE (assignments.created_at <= '2019-04-30 23:59:59')
GROUP BY year(assignments.created_at),month(assignments.created_at)
编辑 您可能不需要WHERE子句