简体   繁体   中英

Group by timestamp in jpql with JPA

guys! I'm trying to group query results by timestamp in JPQL using JPA (EclipseLink + Derby) and use them for creating a Result object. My query is:

Select new com.restaurant.entities.Report(o.timeOfOrder, count(o.id), sum(o.price))";
    queryText+=" from Orders o ";
    queryText+="where o.timeOfOrder BETWEEN :start AND :end";
    queryText+=" group by o.timeOfOrder"

Unluckily, the only one millisec will make a huge difference, thus plain group by o.timeOfOrder doesn't work.

I have tried this approach , however I've got

Internal Exception: java.sql.SQLSyntaxErrorException: Column reference 'ORDERS.TIMEOFORDER' is invalid, or is part of an invalid expression.  For a SELECT list with a GROUP BY, the columns and expressions being selected may only contain valid grouping expressions and valid aggregate expressions.

Perhaps, there are any another way out except changing the type of field in DB?

Your query would have to look something like this:

Select new com.restaurant.entities.Report(o.timeOfOrder, count(o.id), sum(o.price)) 
from Orders o 
where o.timeOfOrder BETWEEN :start AND :end 
group by year(o.timeOfOrder), month(o.timeOfOrder), day(o.timeOfOrder)

but the year , month and day functions are not jpql standard so you have to use FUNCTION to use your equivalent DB functions to perform what you want. Here's more: https://stackoverflow.com/a/3676865/534877

The issue solves rather simply with a use of FUNCTION('period', fieldToTrim). However GROUPing BY result, you should bear in mind, that 'period' (not fieldToTrim) must (!) be in SELECT part, not only in GROUP BY.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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