2016-11-07 18 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爲空時) –