[英]Comparing Date with datetime format
How do I shorten the following statement: 如何缩短以下语句:
select * from orders
where to_char(trunc(Cancel_Date,'MONTH'),'dd/mm/yyyy')='01/03/2015'
and state = 'Cancelled'
and to_date(to_char(trunc(Order_Date,'MONTH'),'dd/mm/yyyy'),'dd/mm/yyyy') < to_date('01/03/2015','dd/mm/yyyy')
It looks like you're trying to retrieve orders that were ordered before March but cancelled in March? 看来您要检索三月之前订购但三月取消的订单? If so, I would avoid filters like this: to_char(trunc(Cancel_Date,'MONTH'),'dd/mm/yyyy')='01/03/2015'
; 如果是这样,我将避免使用以下过滤器: to_char(trunc(Cancel_Date,'MONTH'),'dd/mm/yyyy')='01/03/2015'
; if you have an index on cancel_date
, then it won't be used (except on the off chance that you have a function-based index on that column!). 如果您在cancel_date
上有一个索引,则将不使用该索引(除非极有可能在该列上具有基于函数的索引!)。 I would do the following: 我将执行以下操作:
SELECT * FROM orders
WHERE status = 'Cancelled'
AND cancel_date >= DATE'2015-03-01'
AND cancel_date < DATE'2015-04-01'
AND order_date < DATE'2015-03-01';
In the above query I am using ANSI date literals (supported in Oracle since 9i, I believe) rather than using TO_CHAR()
, TO_DATE()
, etc. And I am not applying any functions to cancel_date
or order_date
so that the optimizer can use the indexes on those columns (if they exist). 在上面的查询中,我使用的是ANSI日期文字(我相信9i以来在Oracle中受支持),而不是使用TO_CHAR()
, TO_DATE()
等。并且我没有对cancel_date
或order_date
应用任何函数,因此优化程序可以使用这些列上的索引(如果存在)。
On a side note using SELECT *
rather than explicitly naming the columns you need is generally not considered a best practice. 附带说明,通常不认为使用SELECT *
而不是显式命名所需的列是最佳实践。
in the second part of the where condition truncate isn't necessary: 在不需要截断条件的第二部分中:
select *
from orders
where to_char(trunc(Cancel_Date,'MONTH'),'dd/mm/yyyy')='01/03/2015'
and state = 'Cancelled'
and Order_Date < to_date('01/03/2015','dd/mm/yyyy')
The function trunc returns a date. trunc函数返回一个日期。 You don't need to convert that to char and back to date again. 您无需将其转换为char并再次恢复为最新状态。
where trunc(Cancel_Date,'MONTH') = to_date('01/03/2015','dd/mm/yyyy')
and state = 'Cancelled'
and trunc(Order_Date,'MONTH') < to_date('01/03/2015','dd/mm/yyyy')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.