如何在 CASE 中使用 BETWEEN

how to using BETWEEN in CASE

所以我想举个例子,如果在接受年份和当前年份 (sysdate) 之间是 1 到 5,它将排名 1 和 6 到 10 排名 2

我使用这样的代码

select first_name,
       case trunc(months_between(sysdate, hire_date) / 12)
         when between 1 and 5 then
          '1'
         when between 6 and 10 then
          '2'
         when between 11 and 15 then
          '3'
         else
          '4'
       end as information
  from employees;

但是在 1 和 5

之间的时候它说 'missing keyword' 是错误的

在哪里 EMPLOYEES table 包含 EMPLOYEE_IDFIRST_NAMEHIRE_DATE

因为表达式应该单独写在每个 when 子句之后,例如

select first_name,
       case 
         when trunc(months_between(sysdate, hire_date) / 12) between 1 and 5 then
          '1'
         when trunc(months_between(sysdate, hire_date) / 12) between 6 and 10 then
          '2'
         when trunc(months_between(sysdate, hire_date) / 12) between 11 and 15 then
          '3'
         else
          '4'
       end as information
  from employees;

或更优雅的选择是

with emp(first_name,year_diff) as
(
 select first_name, trunc(months_between(sysdate, hire_date) / 12) from employees
)
select first_name,
       case 
         when year_diff between 1 and 5 then
          '1'
         when year_diff between 6 and 10 then
          '2'
         when year_diff between 11 and 15 then
          '3'
         else
          '4'
       end as information
  from emp;