0

I got such SQL query:

SELECT COUNT(count) as ovcount from (SELECT COUNT(id) AS count FROM table WHERE
field1=value1 and field2=value2 GROUP BY something1, something2, something3)
as T WHERE count > 1

How would that statement look in HQL? Hibernate doesn't support "the easy way" if a query contains subquery after FROM.

1 Answer 1

1

In the end what I think you're trying to do is to get only COUNT(id) if the total is higher than 1. Using HAVING should give you the same result.

SELECT COUNT(id) AS count 
FROM table 
WHERE field1=value1 and field2=value2 
GROUP BY something1, something2, something3
HAVING COUNT(id) > 1
Sign up to request clarification or add additional context in comments.

3 Comments

Not quite. What you suggest is simply gonna return a set of rows where count > 1. What I want is get a one value, which is the count of that set. (F.e. what you suggest is gonna return: row 1 - count 2, row 2 - 2, row 3 - 3, and I want to get 7 (2+2+3))
OK, I see, thanks for clarifying. Then, one possible solution would be to get the list of results and sum them programmatically. If you still want to do it in one single HQL statement, I cannot think of anything at this moment. As you mentioned, HQL doesn't support subqueries in the FROM clause (only in SELECT and WHERE)
I actally made a mistake, in the second phase I wanted to return 3 - the number of row, not 7 the sum of values. So your solution is good (I actually stumbled upon it in the meantime). I was just wondrering if it's optimal compared to returning the same result by a query alone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.