仅查找两个日期之间的特定日期

时间:2013-02-20 06:26:03

标签: oracle date date-math

我有一个包含如下数据的Oracle表:

 1. ID           DATE 
 2. 12           02/11/2013
 3. 12           02/12/2013
 4. 13           02/11/2013
 5. 13           02/12/2013
 6. 13           02/13/2013
 7. 13           02/14/2013
 8. 14           02/11/2013
 9. 14           02/12/2013
10. 14           02/13/2013

我只需找到那些只有周一,周二和周三日期的ID,所以这里只返回ID = 14。我使用的是Oracle,日期格式为MM / DD / YYYY。 请指教。

此致 尼丁

3 个答案:

答案 0 :(得分:4)

如果日期列是DATE数据类型,则可以

select id
from your_table
group by id
having sum(case 
           when to_char(date_col,'fmday') 
                in ('monday','tuesday','wednesday') then 1
           else 99
           end) = 3;

编辑在igr的观察中核实上述代码

但是,只有当你没有一天两次使用同一个id时,这才行。

如果列是varchar2,则条件变为to_char(to_date(your_col,'mm/dd/yyyy'),'fmday') in ...

更强大的代码是:

select id 
from(
    select id, date_col
    from your_table
    group by id, date_col
)
group by id
having sum(case 
           when to_char(date_col,'fmday', 'NLS_DATE_LANGUAGE=ENGLISH') 
                    in ('monday','tuesday','wednesday') then 1
           else 99
           end) = 3;

答案 1 :(得分:1)

做类似

的事情
SELECT * FROM your_table t 
      where to_char(t.DATE, 'DY') in ('whatever_day_abbreviation_day_you_use');

或者,如果您愿意,可以使用如下的日期编号:

SELECT * FROM your_table t 
     where  to_number(to_char(d.ts, 'D')) in (1,2,3);

如果你想避免ID重复添加DISTINCTION

SELECT DISTINCT ID FROM your_table t 
     where  to_number(to_char(d.ts, 'D')) in (1,2,3);

答案 2 :(得分:1)

select id 
from (
  select 
     id, 
     sum (case when to_char(dt, 'D', 'nls_territory=AMERICA') between 1 and 3 then 1 else -1 end) AS cnt
  from t
  group by id
)
where cnt=3

注意:我假设(id,dt)是唯一的 - 没有两行具有相同的id和日期。

相关问题