2017-02-16 80 views
0

我无法在我有的symfony2项目中得到这个查询。如何在DQL中使用GROUP BY获取每个组中的最新记录?

我表: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行按下列查询排序,但它仍然返回找到的第一行:

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

我感谢你的帮助。

+0

选择所有内容后按顺序排列顺序,而不是按照您的意愿顺序排列。 – Linkan

+0

感谢@Linkan,我明白,但您是否知道如何获得该解决方案?我需要能够以降序搜索,直到找到每个学生的第一行,这将是该案例中记录的最后一行。 – Joseph

+0

要走的路是SELECT id_student,MAX(Academic_year)AS Academic_year FROM表名GROUP BY id_student在加入id_student和学年的最后课程之后。 – Linkan

回答

1

我终于解决了下面的查询问题:

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

我的问题是,我使用了相同的别名的子查询,因为它发生在另一个类似的情况here,我不记得了。

希望有所帮助。

相关问题