2015-08-20 165 views
0

我有一列可能有多个记录,但有时它可能没有。在Oracle的同一列中的多个记录之间选择

Item  Date   quantity 
1   Default  10 
2   Default  10 
2   27-Nov-2015 30 

当日期符合条件时,我需要选取确切的记录。如果当前日期匹配项目2,那么我需要选择数量为30,否则我需要选择默认值。对于第1项,由于没有特定的日期,我总是需要选择数量10.

需要帮助在Oracle查询中编写此代码。

+0

其中的标准来自哪里? –

+0

标准是当前日期(只是简单的sys日期)。如果当前日期与该列上的特定日期相同,则选择数量,否则选择默认值的数量。 – user3723562

回答

0

你可以用UNION ALL解决这个问题。一部分获取当前日期记录,一部分获取默认记录以防当前日期记录存在。尽管使用UNION ALL的你总是会得到一个记录,一个或另一个:

select * 
from mytable 
where item = :item 
and date = to_char(sysdate, 'dd-mon-yyyy', 'NLS_DATE_LANGUAGE=AMERICAN') 
union all 
select * 
from mytable 
where item = :item 
and date = 'Default' 
and not exists 
(
    select * 
    from mytable 
    where item = :item 
    and date = to_char(sysdate, 'dd-mon-yyyy', 'NLS_DATE_LANGUAGE=AMERICAN') 
); 

另一种方法是排名与ROW_NUMBER你的记录,如给予更好的战绩行号#1,并保持这样的:

select item, date, quantity 
from 
(
    select 
    mytable.*, 
    row_number() over (order by case when date = 'Default' then 2 else 1 end) rn 
    from mytable 
    where item = :item 
    and date in (to_char(sysdate,'dd-mmm-yyyy', 'NLS_DATE_LANGUAGE=AMERICAN'), 'Default') 
) 
where rn = 1; 
0

一种方式做,这类型的优先的是使用union allnot exists

select t.* 
from table t 
where date = '27-Nov-2015' 
union all 
select t.* 
from table t 
where not exists (select 1 
        from table t2 
        where t2.item = t.item and t2.date = '27-Nov-2015' 
       ) and 
     t2.date = 'Default'; 

如果你只想要结果的一个项目,我更喜欢这种方法:

select t.* 
from (select t.* 
     from table t 
     where item = :v_item 
     order by (case when date = 'Default' then 1 else 2 end) desc 
    ) t 
where rownum = 1; 
+0

谢谢大家! – user3723562

相关问题