MYSQL:条件A满足时从表中选择一个日期;如果date为空,则从条件B

时间:2019-05-22 04:06:21

标签: sql oracle oracle11g

我正在尝试从ISO_DATE表中选择DATE_VALUEDATE_QUAL_CD=EFFD时。如果上述日期为空或没有DATE_QUAL_CD=EFFD的记录,则返回DATE_VALUE,其中DATE_QUAL_CD=PRIM. 我在下面尝试过:

SELECT ISOD.DATE_VALUE
FROM ISO_DATE ISOD
WHERE
(
 (ISOD.DATE_QUAL_CD ='EFFD' AND ISOD.DATE_VALUE IS NOT NULL)
 OR
 (ISOD.DATE_QUAL_CD ='PRIM'
 AND EXISTS (SELECT 1 FROM ISO_DATE INNERISOD
              WHERE INNERISOD.DATE_QUAL_CD ='EFFD'
              AND INNERISOD.DATE_VALUE IS NULL
              AND ISOD.DATE_ID = INNERISOD.DATE_ID
              )
  )
 )

1 个答案:

答案 0 :(得分:1)

通过DATE_QUAL_CD对行进行排名怎么样?

在此示例中,EFFD存在,因此返回其DATE_VALUE(100):

SQL> with iso_date (date_value, date_qual_cd) as
  2    (select 100, 'EFFD' from dual union all
  3     select 200, 'PRIM' from dual union all
  4     select 300, 'XXXX' from dual
  5    ),
  6  temp as
  7    (select date_value,
  8         date_qual_cd,
  9         rank() over (order by case when date_qual_cd = 'EFFD' then 1
 10                                    when date_qual_cd = 'PRIM' then 2
 11                                    else 3
 12                               end) rn
 13     from iso_date
 14    )
 15  select date_value
 16  from temp
 17  where rn = 1;

DATE_VALUE
----------
       100

SQL>

在此示例中,EFFD不存在,因此返回了PRIM的{​​{1}}(200):

DATE_VALUE

如果SQL> with iso_date (date_value, date_qual_cd) as 2 (select 100, 'ABCD' from dual union all 3 select 200, 'PRIM' from dual union all 4 select 300, 'XXXX' from dual 5 ), 6 temp as 7 (select date_value, 8 date_qual_cd, 9 rank() over (order by case when date_qual_cd = 'EFFD' then 1 10 when date_qual_cd = 'PRIM' then 2 11 else 3 12 end) rn 13 from iso_date 14 ) 15 select date_value 16 from temp 17 where rn = 1; DATE_VALUE ---------- 200 SQL> EFFD都不存在,则上述查询将返回所有行。您没有说在那种情况下该怎么做,所以-现在-这就是您所得到的。