Question

I am trying to get the day month and year of s.eventTime by using:

DAY(s.eventTime) as theDay, MONTH(s.eventTime) as theMonth, YEAR(s.eventTime) as theYear

Then later I use GROUP BY theYear, theMonth, theDay

This gives me the error: org.hibernate.exception.SQLGrammarException: Unknown column 'theYear' in 'group statement'

I have used this method before in SQL, and was wondering if it is invalid in HQL? If so, does anyone have a suggestion?

Was it helpful?

Solution

Don't use aliases on columns. Refer to them by their name. Like on this example from http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-grouping

select cat
from Cat cat
    join cat.kittens kitten
group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc

OTHER TIPS

It seems that you can't cast day(), month(), or year() with as so instead I made my selects like:

DAY(s.eventTime), MONTH(s.eventTime), YEAR(s.eventTime)

Then grouped the same way with:

GROUP BY DAY(s.eventTime), MONTH(s.eventTime), YEAR(s.eventTime)

Expressions such as second(...), minute(...), hour(...), day(...), month(...), and year(...) can only be used in the where clause.

If you need to execute a query that cannot be produced via HQL you can always make a view in your database and map the view as an entity with Hibernate. It works the same way as a table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top