4

我有一个 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 中)。

提前致谢

4

2 回答 2

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
于 2013-02-18T06:44:30.990 回答
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.这里
2.这个符合你的要求

于 2013-02-18T06:49:33.080 回答