SQL根据日期选择号码

时间:2016-05-31 16:02:03

标签: sql oracle

我的数据如下:

 Numbers     Effdate     End_date
2017937950  10/31/2010  4/8/2014 11:59:59 PM
2017937950  10/31/2010  6/30/2011 11:59:59 PM
4054631308  5/9/2008    12/31/2099
4054631308  5/9/2008    7/14/2009 11:59:59 PM
7062329778  10/28/2009  12/31/2099
7062329778  10/28/2009  11/10/2009 11:59:59 PM

我只需要选择那些有end_date 12/31/2099的数字, 所以数据看起来像下面的数据:

  Numbers     Effdate     End_date
4054631308  5/9/2008    12/31/2099
4054631308  5/9/2008    7/14/2009 11:59:59 PM
7062329778  10/28/2009  12/31/2099
7062329778  10/28/2009  11/10/2009 11:59:59 PM

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用in子句

选择相关的行
 select * from my_table 
 where numbers in (select distinct numbers from my_table 
                     where end_date  = to_date('12/31/2099', 'DD/MM/YYYY'));

答案 1 :(得分:0)

使用存在:通常最快;但只允许访问其中一个表中的数据。

Select Numbers, EffDate, End_Date 
from table B
where exists (Select 1 from table A 
              where A.end_Date = to_date('12/31/2099', 'DD/MM/YYYY')  
                 and A.Numbers= B.Numbers)

使用连接:(允许访问已连接的两个表的所有列。

Select Numbers, EffDate, End_Date 
from table B
INNER JOIN (Select Distinct Numbers from table 
            where end_date = to_date('12/31/2099', 'DD/MM/YYYY'))

答案 2 :(得分:0)

您可以使用分析函数来实现此目的:

with sample_data as (select 2017937950 Numbers, to_date('10/31/2010', 'mm/dd/yyyy') Effdate, to_date('04/08/2015 23:59:59', 'mm/dd/yyyy hh24:mi:ss') End_date from dual union all
                     select 2017937950 Numbers, to_date('10/31/2010', 'mm/dd/yyyy') Effdate, to_date('04/08/2015 23:59:59', 'mm/dd/yyyy hh24:mi:ss') End_date from dual union all
                     select 4054631308 Numbers, to_date('05/09/2008', 'mm/dd/yyyy') Effdate, to_date('12/31/2099 00:00:00', 'mm/dd/yyyy hh24:mi:ss') End_date from dual union all
                     select 4054631308 Numbers, to_date('05/09/2008', 'mm/dd/yyyy') Effdate, to_date('07/14/2009 23:59:59', 'mm/dd/yyyy hh24:mi:ss') End_date from dual union all
                     select 7062329778 Numbers, to_date('10/28/2009', 'mm/dd/yyyy') Effdate, to_date('12/31/2099 00:00:00', 'mm/dd/yyyy hh24:mi:ss') End_date from dual union all
                     select 7062329778 Numbers, to_date('10/28/2009', 'mm/dd/yyyy') Effdate, to_date('11/10/2009 23:59:59', 'mm/dd/yyyy hh24:mi:ss') End_date from dual)
select numbers,
       effdate,
       end_date
from   (select numbers,
               effdate,
               end_date,
               max(end_date) over (partition by numbers) max_end_date
        from   sample_data)
where  max_end_date = to_date('12/31/2099', 'mm/dd/yyyy');

   NUMBERS EFFDATE               END_DATE             
---------- --------------------- ---------------------
4054631308 05/09/2008 00:00:00   12/31/2099 00:00:00  
4054631308 05/09/2008 00:00:00   07/14/2009 23:59:59  
7062329778 10/28/2009 00:00:00   12/31/2099 00:00:00  
7062329778 10/28/2009 00:00:00   11/10/2009 23:59:59