views:

6870

answers:

6

Is there any way to do the following in HQL:

SELECT 
    case when flag = true then SUM(col1) else SUM(col2)
FROM 
    myTable
+2  A: 

I guess you can [inline edit] ...for where-clauses:

"Simple" case, case ... when ... then ... else ... end, and "searched" case, case when ... then ... else ... end

Henrik Paul
thanks for the reply... unfortunately this is for the where clause not the select statement.
lomaxx
Ah, would you look at that. Sorry for reading it sloppily
Henrik Paul
no problems.. thanks for contributing in any case
lomaxx
+3  A: 

Apparently the ability to do this was added in 3.0.4, with the limitation that you cannot use sub-selects in the else clause.

Hilton Campbell
thanks for the post. Unfortunately this is only for Hibernate and not NHibernate... but hopefully with it being in Hibernate it shouldn't be too far away before it's in NHibernate
lomaxx
A: 

Below you can find a working query (hibernate on postgresql) that uses 2 case statements to replace a boolean value with the corresponding textual representation.

SELECT CASE ps.open WHEN true THEN 'OPEN' else 'CLOSED' END, CASE ps.full WHEN true THEN 'FULL' else 'FREE' END, ps.availableCapacity FROM ParkingState as ps

Ruben
A: 

This is not working. Following exception is occuring :-

"undefined alias or unknown mapping: case [ select SCTBills.Id ,SCTBills.RABillNo,..."

A: 

This is an example using a string comparison in the condition:

SELECT CASE f.type WHEN 'REMOVE' THEN f.previousLocation ELSE f.currentLocation END FROM FileOperation f

A: 

See Hibernate-Forum: https://forum.hibernate.org/viewtopic.php?t=942197

Answer from Team (Gavin): case is supported in the where clause, but not in the select clause in HB3.

And seen in JIRA with State "Unresolved".

Stephan Prantl
Which JIRA issue did you look at? I found http://opensource.atlassian.com/projects/hibernate/browse/HHH-467 and it's fixed for 3.0.4.
aberrant80