如何将查询转换为HQL?

时间:2019-05-31 21:53:02

标签: sql hibernate spring-data-jpa hql

我在SQL Server中有此查询,该查询使用两个参数startDateendDate

您能否帮助我将其转换为HQL,以使其独立于数据库?

SELECT LeaseTable.CarMake, AVG(LeaseTable.LeaseHours)
FROM
(SELECT lease.carmake, 
    DATEDIFF(HH, case when lease.startDate <@startdate then @startdate else lease.startDate end, dateadd(DD, 1 ,case when lease.endDate > @endDate then @endDate else lease.endDate end)) as LeaseHours
    FROM lease
where 
    lease.startDate <= @endDate AND lease.endDate >= @startdate) as LeaseTable
GROUP BY LeaseTable.carMake 

1 个答案:

答案 0 :(得分:0)

由于JPQL不支持子查询,因此您必须调整查询以获取结果

您可以这样编写查询

String query = "SELECT l.carMake ,"
         + "         AVG("
         + "           DATEDIFF("
         + "             HH,"
         + "             CASE WHEN lease.startDate <:startdate THEN :startdate ELSE lease.startDate end,"
         + "             dateadd(DD, 1 ,case WHEN lease.endDate > :endDate THEN :endDate ELSE lease.endDate end)"
         + "            )"
         + "         )"
         + " FROM lease l"
         + " WHERE l.startDate <= :endDate AND l.endDate >= :startdate"
         + " GROUP BY  l.carMake; ";

基本上,将子查询中的date_diff函数取出到AVG函数中