如何制定IF那么规则作为谓语

时间:2015-07-13 17:41:47

标签: oracle

我有一张包含代码和处理日期的表格。如果代码= 3,则有业务规则说 在某一天,所有代码= 1在这一天应该被压制。

create table test (code number , processing_date date);
insert into test values (1,trunc(sysdate));
insert into test values (2,trunc(sysdate));
insert into test values (3,trunc(sysdate));
insert into test values (1,trunc(sysdate)-1);
insert into test values (2,trunc(sysdate)-1);
commit;

我想到了这个解决方案。它运行正常,但我对谓词的位置非常不满意, 没有评论对我来说不是很直观。我相信我很快就会质疑谓词的含义!

with codes as (
select PROCESSING_DATE,
CODE, 
max(case when code = 3 then 'Y' else 'N' end) over (partition by processing_date) as day_with_c3
from test)
select * from codes
where
-- if there is a day with code = 3 ignore code = 1
 (day_with_c3 != 'Y' OR code != 1)
order by processing_date, code;

还有其他的表述而不是这个可怕的!A或B,更好地描述商业规则的含义如果那么B?

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT * FROM test t
WHERE
  code <> 1 
  OR 
  NOT EXISTS (
    SELECT null FROM test t1
    WHERE t1.processing_date = t.processing_date
      AND code = 3 
    )
 ORDER BY 2,1

演示:http://sqlfiddle.com/#!4/b4cf9/4