【问题标题】:SQL select all distinct rows from first column with random values from other columnsSQL从第一列中选​​择所有不同的行,并从其他列中选择随机值
【发布时间】:2016-09-22 12:55:19
【问题描述】:

我有这样的事情:

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

没有更多的条件,所以我不知道该怎么办。通常我使用partiotion by或group by..请帮助我。

【问题讨论】:

  • 当用户有多个 email2 值时会发生什么?

标签: sql oracle select distinct


【解决方案1】:

鉴于您的样本数据,使用 maxmin 聚合应该会得到您想要的结果:

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

【讨论】:

    【解决方案2】:

    一种方法是:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2021-01-11
      • 2022-06-14
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多