【问题标题】:Selecting from table when two fields satisfy OR condition. And if they satisfy AND condition on same fields select the ones with early date当两个字段满足 OR 条件时从表中选择。如果他们在相同字段上满足 AND 条件,则选择日期较早的字段
【发布时间】:2017-03-29 16:43:18
【问题描述】:
ID1 ID2 DATE INITIAL FINAL
20 328 2016/11/08 01 01
21 328 2016/11/11 01 01
53 766 2016/09/26 00 01
39 766 2016/11/25 01 00

每个 ID2 有两个条目

在上面的示例中,我想选择 INITIAL = 01 or FINAL = 01 的记录,但同时也选择 INITIAL = 01 FINAL = 01 的相同 ID2 的记录,我想要选择日期较早的那个

我正在寻找一个看起来像这样的最终集

ID1 ID2 DATE INITIAL FINAL
20 328 2016/11/08 01 01
53 766 2016/09/26 00 01
39 766 2016/11/25 01 00

【问题讨论】:

    标签: sql oracle select join


    【解决方案1】:

    将您的 2 个案例视为单独的查询,然后将它们合并。 WITH 只是我构建虚拟数据。这不会解决 id2 具有 01 初始和 01 最终以及另一行具有 00 和 01 的情况 --- 但这不在您的要求中。如果您有两个 01 01 行的相同 id2 具有相同的最小日期,它也不会解决这个问题,但同样 - 这不在规范中;我只是想把这些事情说得透彻。

    with records as
      (select 20 as id1, 328 as id2, to_date('2016-11-08','YYYY-MM-DD') as mydate, '01' as myinitial, '01' as myfinal from dual
       union all
       select 21 as id1, 328 as id2, to_date('2016-11-11','YYYY-MM-DD') as mydate, '01' as myinitial, '01' as myfinal from dual
       union all
       select 53 as id1, 766 as id2, to_date('2016-09-26','YYYY-MM-DD') as mydate, '00' as myinitial, '01' as myfinal from dual
       union all
       select 39 as id1, 766 as id2, to_date('2016-11-25','YYYY-MM-DD') as mydate, '01' as myinitial, '00' as myfinal from dual)
    
    select *
    from records
    where (myinitial = '01' or myfinal = '01')
      and myinitial <> myfinal
    
    union 
    
    select *
      from records  r
      where r.myinitial = '01' and r.myfinal = '01'
        and r.mydate =
            (select min(r2.mydate) from records r2
               where r2.myinitial='01' and r2.myfinal='01' and r2.id2 = r.id2)
      ;
    

    【讨论】:

      【解决方案2】:

      在本例中,“OR”包括“AND”

      试试看

      select * from (select  * from myTable where INITIAL = '01' or FINAL = '01' order by Date) where Rownum=1
      

      【讨论】:

        【解决方案3】:

        试试下面的查询。 它将丢弃 INITIAL=00 和 FINAL=00 的行,因为您只想选择 INITIAL = 01 或 FINAL = 01 AND INITIAL = 01 AND FINAL = 01 且日期较早的记录

        SELECT ID1,ID2,DATE,INITIAL,FINAL FROM TEST1 WHERE ID1 NOT IN(SELECT ID1 FROM
        (SELECT ID1,
          ID2,
          DATE,
          INITIAL,
          FINAL,
          RANK() OVER (PARTITION BY ID2 ORDER BY DATE) rn
        FROM TEST1
        WHERE (INITIAL = '01'
        AND FINAL    = '01')
        ) WHERE rn>1  ) AND (INITIAL != '00'OR FINAL!= '00');
        

        【讨论】:

          猜你喜欢
          • 2014-09-21
          • 1970-01-01
          • 1970-01-01
          • 2016-06-13
          • 1970-01-01
          • 2012-06-23
          • 2017-01-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多