繁体   English   中英

如何使用DQL中的GROUP BY获取每个组中的最新记录?

[英]How to get the latest record in each group using GROUP BY in DQL?

我在一个symfony2项目中无法获得此查询。

我的表: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 

我需要为每个学生获取我根据学年获得的最后记录。

通过以下查询,我获得了每个学生的第一行:

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();
}

下表显示了谁的解决方案:

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  

我想要的是根据学年获得最后一行,如下表所示:

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  

为此,我尝试在以下查询中使用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();
} 

我感谢您的帮助。

我终于用以下查询解决了这个问题:

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();
 } 

我的问题是,我用同样的别名子选择,因为它发生在另一个类似的案件在这里 ,我不记得了。

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM