2016-09-22 132 views
-1

我有這樣的事情:SQL從其他列選擇第一列隨機值的所有不同的行

id  email  email2  id_2 
------------------------------------------ 
1  [email protected]  [email protected]  11   
1  [email protected]  [email protected]  11   
1  [email protected]   -   11 
1  [email protected]   -   11 
2  [email protected]  [email protected]  22   
2  [email protected]  [email protected]  44   
3  [email protected]   -   33 
3  [email protected]   -   33   
4  [email protected]  [email protected]   55 

,所以我需要選擇不同的ID的所有值,如果EMAIL2不是空的,我應該選擇一個沒有空電子郵件2,但如果只有空的電子郵件2,請選擇一個。例如:

id  email  email2  id_2 
------------------------------------------ 
1  [email protected]  [email protected]  11    
2  [email protected]  [email protected]  22   
3  [email protected]   -   33   
4  [email protected]  [email protected]   55 

沒有更多的條件,所以我不知道該怎麼做。通常我使用partiotion或group by ..請幫助我。

+0

當用戶有多個email2值時會發生什麼? –

回答

1

鑑於你的樣本數據,使用maxmin總應該得到你想要的結果:

select id, max(email), max(email2), min(id_2) 
from yourtable 
group by id 
+0

謝謝,它的工作! –

0

一種方法是:

select t.* 
from (select t.*, 
      row_number() over (partition by id 
           order by (case when email2 is not null then 1 else 2 end) 
           ) as seqnum 
     from t 
    ) t 
where seqnum = 1; 

這種方法可以讓你拉你想要的任何列從一排電子郵件和兩個電子郵件。

注:這是假定-實際上意味着NULL。如果實際值是連字符,則需要修改case

+0

非常感謝你的蒙克! –

相關問題