Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL group by hours in a time range

I have the following SQL query to group orders by the order date and hour in a day:

select to_char(o.order_date, 'YYYY-MM-DD HH24') order_date_hour,
  sum(o.quantity) quantity
from orders o
where o.order_date >= to_date('01.02.2016', 'DD.MM.YYYY')
  and o.order_date < to_date('03.02.2016', 'DD.MM.YYYY')
group by to_char(o.order_date, 'YYYY-MM-DD HH24')
order by to_char(o.order_date, 'YYYY-MM-DD HH24');

An example for the result is as follows:

ORDER_DATE_HOUR | QUANTITY 
2016-02-01 06   | 10 
2016-02-03 09   | 20

The query works as expected using SQL developer. In QueryDSL I came up with the following query:

SQLQuery q = queryFactory.createSQLQuery();
q.from(order);
q.where(order.orderDate.goe(Timestamp.valueOf(from)))
.where(order.orderDate.lt(Timestamp.valueOf(to)));

q.groupBy(to_char(order.orderDate, "YYYY-MM-DD HH24"));
q.orderBy(order.orderDate.asc());

List<Tuple> result = q.list(to_char(order.orderDate, "YYYY-MM-DD HH24"), order.quantity);

to_char is a method I found in this thread: https://groups.google.com/forum/#!msg/querydsl/WD04ZRon-88/nP5QhqhwCUcJ

The exception I get is:

java.sql.SQLSyntaxErrorException: ORA-00979: not a GROUP BY expression

I tried a few variations of the query with no luck at all.

Does anyone know why the query is failing? Thanks :)

like image 279
Robert M. Avatar asked Apr 11 '16 07:04

Robert M.


1 Answers

You can use StringTemplate and DateTemplate to build custom expressions, like done in the unit test com.querydsl.sql.TemplateTest:

StringTemplate datePath = Expressions.stringTemplate(
    "to_char({0},'{1s}')", order.orderDate, ConstantImpl.create("YYYY-MM-DD HH24"));

DateTemplate from = Expressions.dateTemplate(
    Date.class, "to_date({0},'{1s}')", fromStr, ConstantImpl.create("DD.MM.YYYY"));

DateTemplate to = Expressions.dateTemplate(
    Date.class, "to_date({0},'{1s}')", toStr, ConstantImpl.create("DD.MM.YYYY"));

query.select(datePath.as("order_date_hour"), order.quantity.sum().as("quantity"))
 .from(order)
 .where(order.orderDate.goe(from)
     .and(order.orderDate.lt(to)))
    .groupBy(datePath)
    .orderBy(datePath.asc());

List<Tuple> results = query.fetch();

Here the printout for query.getSQL().getSQL():

select to_char("order".order_date,'YYYY-MM-DD HH24') order_date_hour, sum("order".quantity) quantity
from "order" "order"
where "order".order_date >= to_date(?,'DD.MM.YYYY') and "order".order_date < to_date(?,'DD.MM.YYYY')
group by to_char("order".order_date,'YYYY-MM-DD HH24')
order by to_char("order".order_date,'YYYY-MM-DD HH24') asc
like image 123
Meiko Rachimow Avatar answered Oct 04 '22 23:10

Meiko Rachimow