仅与日期和月份之间的日期

时间:2015-10-14 12:25:37

标签: sql oracle

我有这个日期:

Date1 =  14/10/2015
Date2 =  01/10/2011
Date3 =  01/11/2011

我试图做这个请求:

Date1 between date2 and date3

如何在不注意岁月(仅限sql(oracle))的情况下实现这一点。

请求应该是真的。

由于

4 个答案:

答案 0 :(得分:0)

Oracle 中,您可以获得date1date2的第一天以及date3的最后一天,然后使用以下内容,例如:< / p>

WHERE TRUNC(date1, 'MONTH') BETWEEN TRUNC(date2, 'MONTH') AND LAST_DAY(TO_DATE(date3,'MM/DD/YYYY'))

答案 1 :(得分:0)

作为替代方案,您可以将MMDD的数字表示转换为数字,并检查此数字是否在特定范围内。

select *
from (select to_date('14/10/2015', 'DD/MM/YYYY') as datee from dual union
      select to_date('01/10/2011', 'DD/MM/YYYY') as datee from dual union
      select to_date('01/11/2011', 'DD/MM/YYYY') as datee from dual)
where to_number(to_char(datee,'MMDD')) between 1014 and 1131

答案 2 :(得分:0)

在Oracle中,您可以使用EXTRACT函数获取日期的各个部分并使用它进行比较:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TEST( Date1 ) AS
          SELECT DATE '2015-01-01' FROM DUAL
UNION ALL SELECT DATE '2015-01-15' FROM DUAL
UNION ALL SELECT DATE '2015-02-01' FROM DUAL
UNION ALL SELECT DATE '2015-09-01' FROM DUAL
UNION ALL SELECT DATE '2014-01-10' FROM DUAL
UNION ALL SELECT DATE '2014-01-20' FROM DUAL
UNION ALL SELECT DATE '2014-02-02' FROM DUAL
UNION ALL SELECT DATE '2013-01-14' FROM DUAL

查询1

WITH Dates ( Date2, Date3 ) AS (
  SELECT DATE '2015-01-10', DATE '2015-02-01' FROM DUAL
)
SELECT t.*
FROM   TEST t
       CROSS JOIN Dates d
WHERE  (  EXTRACT( MONTH FROM Date1 ) > EXTRACT( MONTH FROM Date2 )
       OR (    EXTRACT( MONTH FROM Date1 ) =  EXTRACT( MONTH FROM Date2 )
           AND EXTRACT( DAY   FROM Date1 ) >= EXTRACT( DAY   FROM Date2 )
          )
       )
AND    (  EXTRACT( MONTH FROM Date1 ) < EXTRACT( MONTH FROM Date3 )
       OR (    EXTRACT( MONTH FROM Date1 ) =  EXTRACT( MONTH FROM Date3 )
           AND EXTRACT( DAY   FROM Date1 ) <= EXTRACT( DAY   FROM Date3 )
          )
       )

<强> Results

|                      DATE1 |
|----------------------------|
|  January, 15 2015 00:00:00 |
| February, 01 2015 00:00:00 |
|  January, 10 2014 00:00:00 |
|  January, 20 2014 00:00:00 |
|  January, 14 2013 00:00:00 |

答案 3 :(得分:0)

使用DDD格式字符串获取一年中的某一天的数字,即:

select to_char(to_date('14/10/2015','DD/MM/YYYY'),'DDD') d1
      ,to_char(to_date('01/10/2011','DD/MM/YYYY'),'DDD') d2
      ,to_char(to_date('01/11/2011','DD/MM/YYYY'),'DDD') d3
from dual;

D1  D2  D3
=== === ===
287 274 305

with params as (
  select to_date('14/10/2015','DD/MM/YYYY') d1
        ,to_date('01/10/2011','DD/MM/YYYY') d2
        ,to_date('01/11/2011','DD/MM/YYYY') d3
  from dual)
select 'Yes' a from params
where to_char(d1,'DDD') between to_char(d2,'DDD') and to_char(d3,'DDD');

A
===
Yes