簡體   English   中英

Oracle獲得一個月內的所有日期

[英]Oracle get all dates in a month

我正在嘗試編寫一條SQL語句,該語句將允許我檢索9月份創建的所有訂單,但運氣不佳。

無法運作:

select order_number, created_date
from orders
where created_date in to_date('2012-09', 'YYYY-MM');

工作但時間太長:

select order_number, created_date
from orders
where trunc(created_date) between to_date('2012-09-01', 'YYYY-MM-DD') and to_date('2012-09-30', 'YYYY-MM-DD');

怎么樣:

select order_number, created_date
from orders
where created_date >= to_date('2012-09-01', 'YYYY-MM-DD') 
and created_date < to_date('2012-10-01', 'YYYY-MM-DD');

您應該嘗試保持created_date不變,以確保可以很好地利用索引。

使用以下代碼。

select order_number, created_date
from orders
where TO_CHAR(created_date, 'YYYY-MM') in '2012-09';

我認為您between使用的版本會具有更好的性能,但是您始終可以嘗試其他方法:

WHERE TO_CHAR(created_date, 'YYYY-MM') = '2012-09';

另一種選擇是EXTRACT

WHERE 
  EXTRACT(year FROM created_date) = 2012 
  AND EXTRACT(month FROM created_date) = 9;

更新:

Oracle 8i開始 ,可以使用基於函數的索引來改善這種查詢的性能:

CREATE INDEX ORDS_CRTD_DT_YYYY_MM_IDX 
   ON orders (TO_CHAR(created_date, 'YYYY-MM'));

當然,當有更簡單的解決方案時(例如提供的@Rob),應避免無故創建索引(它們會減慢寫操作的速度)。 只需記住,可以對列使用TRUNCTO_CHAREXTRACT功能,並且仍然避免完全掃描。

無需通過between使用來重復created_date列,即使查詢繼續利用該列上的索引(如果有的話)也可以通過使用trunc(to_date('2012-09','yyyy-mm'),'Month')第一個日期為last_day(to_date('2012-09','yyyy-mm'))為該月的最后日期。

with orders(order_number, created_date) as
(
 select 1, date'2012-08-31' from dual union all
 select 2, date'2012-09-01' from dual union all
 select 3, date'2012-09-02' from dual union all
 select 4, date'2012-09-29' from dual union all   
 select 5, date'2012-09-30' from dual union all   
 select 6, date'2012-10-01' from dual    
),
  param(month) as
(
 select to_date('2012-09','yyyy-mm') from dual    
)    
select order_number, created_date 
  from orders
 cross join param
 where created_date between trunc(month,'Month')
                        and last_day(month);

ORDER_NUMBER    CREATED_DATE
------------    ------------
2               01.09.2012 
3               02.09.2012 
4               29.09.2012 
5               30.09.2012 

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM