我有一列可能有多個記錄,但有時它可能沒有。在Oracle的同一列中的多個記錄之間選擇
Item Date quantity
1 Default 10
2 Default 10
2 27-Nov-2015 30
當日期符合條件時,我需要選取確切的記錄。如果當前日期匹配項目2,那麼我需要選擇數量爲30,否則我需要選擇默認值。對於第1項,由於沒有特定的日期,我總是需要選擇數量10.
需要幫助在Oracle查詢中編寫此代碼。
我有一列可能有多個記錄,但有時它可能沒有。在Oracle的同一列中的多個記錄之間選擇
Item Date quantity
1 Default 10
2 Default 10
2 27-Nov-2015 30
當日期符合條件時,我需要選取確切的記錄。如果當前日期匹配項目2,那麼我需要選擇數量爲30,否則我需要選擇默認值。對於第1項,由於沒有特定的日期,我總是需要選擇數量10.
需要幫助在Oracle查詢中編寫此代碼。
你可以用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;
一種方式做,這類型的優先的是使用union all
和not 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;
謝謝大家! – user3723562
其中的標準來自哪裏? –
標準是當前日期(只是簡單的sys日期)。如果當前日期與該列上的特定日期相同,則選擇數量,否則選擇默認值的數量。 – user3723562