[英]How to get the latest record in each group using GROUP BY in DQL?
I can not get this query in a symfony2 project that I have. 我在一个symfony2项目中无法获得此查询。
My Table: Case_file 我的表:Case_file
id id_student last_course Academic_year
---|----------|------------|--------------
1 | 1 | 1º Primary | 2014 / 2015
2 | 2 | 2º Primary | 2014 / 2015
5 | 3 | 1º Primary | 2014 / 2015
3 | 1 | 2º Primary | 2015 / 2016
4 | 2 | 3º Primary | 2015 / 2016
I need to obtain for each student the last record that I have according to the academic year. 我需要为每个学生获取我根据学年获得的最后记录。
With the following query I obtain the first row that is found of each student: 通过以下查询,我获得了每个学生的第一行:
public function findOldEstudent()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE s.active=0 GROUP BY s.id ')
->getResult();
}
Whose solution I show in the following table: 下表显示了谁的解决方案:
id id_student last_course Academic_year
---|----------|------------|--------------
1 | 1 | 1º Primary | 2014 / 2015 *
2 | 2 | 2º Primary | 2014 / 2015 *
3 | 3 | 1º Primary | 2014 / 2015
And what I want is to get the last row according to the academic year, as shown in the following table: 我想要的是根据学年获得最后一行,如下表所示:
id id_student last_course Academic_year
---|----------|------------|--------------
1 | 1 | 2º Primary | 2015 / 2016 *
2 | 2 | 3º Primary | 2015 / 2016 *
3 | 3 | 1º Primary | 2014 / 2015
For this I have tried to sort the rows with ORDER BY in the following query, but it continues to return the first row found: 为此,我尝试在以下查询中使用ORDER BY对行进行排序,但它继续返回找到的第一行:
public function findOldEstudent()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE s.active=0 GROUP BY s.id ORDER BY c.academic_year DESC')
->getResult();
}
I appreciate your help. 我感谢您的帮助。
I finally solved the problem with the following query: 我终于用以下查询解决了这个问题:
public function findOldEstudent()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE c.academic_year IN (select MAX(ca.academic_year) FROM BackendBundle:case_file ca INNER JOIN ca.student st GROUP BY st.id) and s.active=0')
->getResult();
}
The problem I had is that I used the same alias in the subselect, as it happened in another similar case here and I did not remember. 我的问题是,我用同样的别名子选择,因为它发生在另一个类似的案件在这里 ,我不记得了。
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.