如何在查询的 when 子句中对数据 return 使用 where 子句

how to use where clause on the data return from when clause of the query

我有一个看起来像这样的查询。

select case 
           when salary<5000
             then date1
           else date2
       end "app"
from employees
order by app desc;

如果员工的薪水低于 5000,我将打印 date1 列的值;如果员工的薪水大于 5000,我将打印 date2 列的值。现在我想对我从该查询中收到的日期应用进一步的过滤器,即仅显示那些记录返回日期在过去 7 天内的位置。我可以在 order by 子句中使用 "app" 同义词,但是当我尝试在 where 子句中使用它时,它会引发编译时错误。如何应用此过滤器。

注意:此查询要在oracle中执行。

您可以使用 where

过滤结果
select 
   case when salary<5000 then date1 else date2 end "app" 
from employees 
where case when salary<5000 then date1 else date2 end   >= sysdate -7
order by app desc;

您可以在 where 子句中使用整个表达式

SELECT CASE WHEN salary < 5000 THEN date1 ELSE date2 END "app" FROM employees
WHERE  CASE WHEN salary < 5000 THEN date1 ELSE date2 END >= SYSDATE - 7
ORDER  BY "app" DESC;

或将您的原始查询用作子查询:

SELECT "app"
FROM   (SELECT CASE WHEN salary < 5000 THEN date1 ELSE date2 END "app" FROM employees)
WHERE  "app" >= SYSDATE - 7
ORDER  BY "app" DESC;