2016-11-07 17 views
1

我正在尝试进行一个查询,它将调用获取所有匹配的col3 = 1并获取组的其余部分col4 = 123,同时让col2成为不同的值。我的表看起来像在结果中加入某些行

ID col1 col2 col3 col4 
--------------------------------- 
1 A1  A  NULL 123 
2 B1  B  NULL 123 
3 C1  C  NULL 123 
4 D1  D  NULL 123 
5 C2  C  1  123 
6 D2  D  1  123 

,我试图做一个查询,将返回的ID 1,2,5和6试过工会和加入过的select * from tbl where col4 = 123 and col3 =1变化,他们都要么排除3,4,5 ,6或全部包括在内。

+0

我不明白的问题。你想用什么标准来选择行? – Blorgbeard

+0

我基本上想要查询col4 = 123,然后获取所有在col 3中有值的所有值以及与col2不匹配的所有其他值。 – user2920788

回答

2
select  * 


from  (select  * 

         ,row_number() over 
         (
          partition by col2 
          order by  case when col3 = 1 then 1 else 2 end 
         ) as rn 

      from  t 

      where  col4 = 123 
      ) t 

where  col3 = 1 
     or t.rn = 1 
; 
0

如果我理解正确的话,你希望所有行col3NULL,然后剩余行,那些从这些具有不同col2值:

select t.* 
from t 
where t.col4 = 123 and 
     (t.col3 is not null or 
     t.col2 not in (select t.col2 from t t2 where t2.col4 = 123 and t2.col3 is not null) 
    ) 
+0

不要忘记“col4 = 123”的要求 –

+0

@AlvinThompson。 。 。谢谢。 –

+0

我认为“123”要求只适用于第二部分(当t.col3为空时) –