0

我想使用条件获取此 SQL

select A.evaluated_employee_id, A.created_date, A.total_grade
from employee_performance_assessment A
join
(  select evaluated_employee_id, max(created_date) as maxdate, status, total_grade
    from employee_performance_assessment
    group by evaluated_employee_id
) B on A.evaluated_employee_id = B.evaluated_employee_id and A.created_date = B.maxDate

我正在做以下事情

    DetachedCriteria dc = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class);
    dc.createAlias("evaluatedEmployee", "e");
    dc.setProjection(Projections.projectionList().add(Projections.max("createdDate"))
.add(Projections.groupProperty("evaluatedEmployee")));
 dc.addOrder(Order.asc("e.lastName")).addOrder(Order.asc("createdDate"));                   
    dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return getDAOHibernateTemplate().findByCriteria(dc);

但这会在 WHERE 子句中生成子查询知道如何从同一个表(类)中连接两个条件吗?

4

1 回答 1

4

找到解决方案。基本上改变了原来的查询:

select A.evaluated_employee_id, A.created_date, A.total_grade
from employee_performance_assessment A
where A.created_date = 
(  select max(created_date)
    from employee_performance_assessment
    where A.evaluated_employee_id = evaluated_employee_id 
    group by evaluated_employee_id
) 

因此,我没有加入子查询,而是比较 where 子句中的 created_date。而在休眠中的等价物是:

DetachedCriteria dc = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class, "performanceAssessment");
dc.createAlias("evaluatedEmployee", "e");

dc.addOrder(Order.asc("e.lastName")).addOrder(Order.asc("createdDate"));

if (assessmentsSearch.isOnlyLastAssessment()){
   DetachedCriteria dc2 = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class, "performanceAssessmentSubQuery");
   dc2.setProjection(Projections.projectionList().add(Projections.max("createdDate")));
   dc2.add(Expression.eqProperty("performanceAssessment.evaluatedEmployee.id", "performanceAssessmentSubQuery.evaluatedEmployee.id"));

   dc.add(Subqueries.propertyEq("createdDate", dc2));
}

希望它可以帮助别人。

于 2013-10-11T18:00:19.957 回答