我有一个名为Student
的模型,has_many
Test
。每个Test
都有一个名为mark
的列。我想
我被困在我正在为测试标记创建选择查询的部分。
答案 0 :(得分:0)
我认为提供原始SQL查询会更容易,因此对于我认为此查询应该起作用的第一项任务
SELECT students.*, AVG(COALESCE(tests.mark, 0)) as avg_mark FROM students LEFT OUTER JOIN tests ON students.id = tests.student_id GROUP BY students.id ORDER BY avg_mark
对于我使用this帖子的第二项任务,我认为它应该有用,但没有检查
SELECT students.*, MIN(LAG(COALESCE(tests.mark, 0)) OVER (ORDER BY tests.mark) as mark_diff) as min_mark FROM students LEFT OUTER JOIN tests ON students.id = tests.student_id GROUP BY students.id ORDER BY min_mark
我没有完全理解上一个任务。我认为这是学生测试之间的最大差异
SELECT students.*, MIN(LAG(COALESCE(tests.mark, 0)) OVER (ORDER BY tests.mark) as mark_diff) as min_mark FROM students LEFT OUTER JOIN tests ON students.id = tests.student_id GROUP BY students.id ORDER BY min_mark
为了让它更有轨道,试试这个:
Student.select('students.*, MIN(LAG(COALESCE(tests.mark, 0)) OVER (ORDER BY tests.mark) as mark_diff) as min_mark').joins('LEFT OUTER JOIN tests ON students.id = tests.student_id').group('students.id').order('min_mark')
但是在聚合函数之后,您将无法向结果关系添加任何范围。您可以尝试对其进行两次查询,为结果提供ID列表
scope :my_scope, -> { ids = my_request.pluck(:id); where(id: ids) }
可能的陷阱是最大查询大小。