[英]SQL select all distinct rows from first column with random values from other columns
我有這樣的事情:
id email email2 id_2
------------------------------------------
1 James@ james2@ 11
1 James@ james2@ 11
1 James@ - 11
1 James@ - 11
2 Declan@ dylan2@ 22
2 Declan@ dylan2@ 44
3 John@ - 33
3 John@ - 33
4 Vito@ vito2@ 55
所以我需要為不同的 id 選擇所有值,如果 email2 不為空,我應該選擇一個不為空的 email2,但如果只有空的 email2,請選擇一個。 例如:
id email email2 id_2
------------------------------------------
1 James@ james2@ 11
2 Declan@ dylan2@ 22
3 John@ - 33
4 Vito@ vito2@ 55
沒有更多的條件,所以我不知道該怎么做。 通常我使用 partition by 或 group by .. 請幫助我。
給定您的樣本數據,使用max
或min
聚合應該可以獲得您想要的結果:
select id, max(email), max(email2), min(id_2)
from yourtable
group by id
一種方法是:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.