Hibernate, how to count with condition

末鹿安然 提交于 2019-12-10 10:36:21

问题


I am using oracle and hibernate for mapping. I want to count with a condition in count() function. my code is:

select count(case when st.averageMark < su.gradePass then 1 else 0 end) from Study st join st.subject su where st.acaYear in (2009) and st.semester = 4 and su.idSeq = 1330 group by st.acaYear

the code return me nothing. I used sum instead of count it returned a result but it is wrong, the result is bigger than I suppose it to be.

thank in advance.


回答1:


I just solved the problem with the following code.

select sum(case when st.averageMark >= su.gradePass then 1 else 0 end) as pass,
       sum(case when  st.averageMark < su.gradePass then 1 else 0 end) as fail
from Study st join st.subject su
where st.acaYear in (2009) and st.semester = 4 and su.idSeq = 1330
group by st.acaYear



回答2:


Combining Nathanphan's answer and M. A. Khomeni's comment,

CASE is not supported in COUNT()

So we need to use SUM() instead of COUNT()

For Example:

COUNT(CASE WHEN st.averageMark < su.gradePass THEN 1 ELSE 0 END)

Should be written as

SUM(CASE WHEN st.averageMark < su.gradePass THEN 1 ELSE 0 END)


来源:https://stackoverflow.com/questions/5295626/hibernate-how-to-count-with-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!