是否有任何其他逻辑或更强大的方式

时间:2013-02-18 06:38:46

标签: sql oracle hibernate select

我有一个SQL查询

select count(salary)
from USER_DETAILS 
where salary>0 and salary<1000 union all
select count(salary)
from USER_DETAILS 
where salary>1000 and salary<10000 union all
select count(salary)
from USER_DETAILS 
where salary>10000 and salary<100000

是否有任何其他逻辑或更健壮的方法来执行相同的查询(最好是在hql中)。

提前致谢

2 个答案:

答案 0 :(得分:6)

尝试一下,

SELECT  COUNT(CASE WHEN salary >= 0 and salary <= 1000 THEN salary END) "salary >= 0 and salary <= 1000",
        COUNT(CASE WHEN salary >= 1000 and salary <= 10000 THEN salary END) "salary >= 1000 and salary <= 10000",
        COUNT(CASE WHEN salary >= 10000 and salary <= 100000 THEN salary END) "salary >= 10000 and salary <= 100000"
from    user_details

答案 1 :(得分:3)

使用CASE声明

尝试
select  
     count(case when sal between 0 and 1000 then 1 end)
     count(case when sal between 1000 and 10000 then 1 end) ,
     count(case when sal between 10000 and 100000 then 1 end)
from user_details;

注意:您还可以将else关键字放在最后(如果需要)

例如,请参阅
 1. here
 2. This one goes with your requirement