【问题标题】:Is there any other logical or more robust way有没有其他合乎逻辑或更稳健的方式
【发布时间】:2013-02-02 13:21:03
【问题描述】:

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

提前致谢

【问题讨论】:

  • 可能是case 声明会有所帮助
  • 到目前为止还没有使用过 case 不知道它是否会起作用 您可以使用“case”或使用“case”的任何此类链接提供该查询。顺便说一句
  • 感谢@asifsid88 我得到了解决方案

标签: sql oracle hibernate select


【解决方案1】:

试试看,

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

【讨论】:

  • @CodeHunter - 你应该“接受”JW 的回答,因为它对你有用。
【解决方案2】:

使用 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

【讨论】:

  • 您知道这只会返回 1 条记录(1 行 1 列)吗?
  • 是的,我是这么认为的,但它提供了一些“不是单组功能”
猜你喜欢
  • 2020-12-01
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
相关资源
最近更新 更多