SQL从其他列选择第一列随机值的所有不同的行
问题描述:
我有这样的事情: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 ..请帮助我。
答
鉴于你的样本数据,使用max
或min
总应该得到你想要的结果:
select id, max(email), max(email2), min(id_2)
from yourtable
group by id
+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
非常感谢你的蒙克! –
当用户有多个email2值时会发生什么? –