Oracle SQL case 条件涉及一列但改变另一列

Oracle SQL case condition involving one column but changing another

我正在尝试将任何 sortest_test_date 大于 5 年的元组的 sortest_tesc_code 更改为 ZZZ

select sortest_pidm, sortest_tesc_code 
     case sortest_tesc_code 
     when extract(year from sysdate)-extract(year from sortest_test_date)>=5 then 'ZZZ' 
          else sortest_tesc_code end as sortest_tesc_code
from tempTbl2

假设 tempTbl2(派生的)是这样的:

示例数据:

MOD7    1   10-JAN-11
MOD9    1   10-JAN-11
MPA3    1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

更改为:

ZZZ     1   10-JAN-11
ZZZ     1   10-JAN-11
ZZZ     1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

您只是对 CASE 语法有点困惑。

select
   case when extract(year from sysdate) - extract(year from sortest_test_date) >= 5 
     then 'ZZZ' 
     else sortest_tesc_code
  end as new_sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2
order by sortest_test_date, sortest_tesc_code;

您正在混合使用简单和搜索的 case 表达式语法;你对 'five years' 的计算有点奇怪 - 我会根据两个日期之间的月份来计算,而不仅仅是看年份数字:

with tempTbl2(sortest_tesc_code, testscore, sortest_test_date) as (
  select 'MOD7', 1, date '2011-01-10' from dual union all
  select 'MOD9', 1, date '2011-01-10' from dual union all
  select 'MPA3', 1, date '2011-07-19' from dual union all
  select 'C012', 3, date '2018-07-01' from dual union all
  select 'C030', 3, date '2017-07-01' from dual union all
  select 'MPA2', 1, date '2018-07-12' from dual
)
select
  case
    when add_months(sysdate, -60) > sortest_test_date then 'ZZZ' 
    else sortest_tesc_code
  end as sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2
SORTEST_TESC_CODE TESTSCORE SORTEST_TEST_DATE
ZZZ 1 10-JAN-11
ZZZ 1 10-JAN-11
ZZZ 1 19-JUL-11
C012 3 01-JUL-18
C030 3 01-JUL-17
MPA2 1 12-JUL-18

db<>fiddle


使用extract(year from sysdate)-extract(year from sortest_test_date)>=,2018-01-01之前的任何日期都将匹配;将截至今天仅 4 年零 42 天前的日期视为 5 年多前的日期对我来说似乎是错误的。当然,也许您有正当理由这样做,在这种情况下,只需将条件改回原来的状态即可。