Hibernate: Implement a SELECT with GROUP BY and aggregate functions

时间:2016-07-11 19:44:12

标签: java hibernate aggregate

I want to:

SELECT date(some_date), SUM(value1 * value2)
FROM some_table
WHERE id = 1
GROUP BY date(some_date)
ORDER BY id DESC;

But I have no idea how to convert it to Hibernate syntax, especially the date(some_date) part and SUM(value1 * value2) parts

1 个答案:

答案 0 :(得分:0)

Lets imagine that you have mapped you take some_table to a class named SomeTable. Your HQL query will look like this:

select to_char(t.someDate, 'yyyy-mm-dd'), sum(t.value1*t.value2)
from SomeTable t 
group by to_char(t.someDate, 'yyyy-mm-dd')
order by t.id desc;

What is important to be noted here is that you need to cast the date to a char in order to group by it.