How to query for a specific day of the month in Oracle

后端 未结 3 1532
轻奢々
轻奢々 2021-01-26 19:19

Trying to automate a query that will pull data for the current month where the day of the month (in the date field) is >= the 15th. Is this possible? If so, what is the syntax t

相关标签:
3条回答
  • 2021-01-26 19:30

    If your date/time fields are of type timestamp you can do

    select x from <your_table>
    where EXTRACT(DAY from <timestamp field>) >=15
    and EXTRACT(MONTH from <timestamp field>) = EXTRACT(MONTH FROM CURRENT_TIMESTAMP)
    and EXTRACT(YEAR from <timestamp field>)  = EXTRACT(YEAR FROM CURRENT_TIMESTAMP);
    
    0 讨论(0)
  • 2021-01-26 19:52

    This will allow you to use any indexes you have on your date_field column:

    SELECT *
    FROM   table_name
    WHERE  date_field >= TRUNC( SYSDATE, 'MM' ) + INTERVAL '14' DAY
    AND    date_field <  ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 );
    
    0 讨论(0)
  • 2021-01-26 19:52

    I think what you're after is something like:

    with sample_data as (select 1 id, to_date('01/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 2 id, to_date('10/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 3 id, to_date('14/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 4 id, to_date('15/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 5 id, to_date('16/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 6 id, to_date('30/06/2016', 'dd/mm/yyyy') dt from dual union all
                         select 7 id, to_date('01/07/2016', 'dd/mm/yyyy') dt from dual)
    select *
    from   sample_data
    where  dt >= trunc(sysdate, 'mm') + 14
    and    dt < last_day(trunc(sysdate)) + 1;
    
            ID DT        
    ---------- ----------
             4 15/06/2016
             5 16/06/2016
             6 30/06/2016
    

    (If you wanted rows with any date greater than the 15th of the current month, then remove the last predicate in the where clause.)

    0 讨论(0)
提交回复
热议问题