【问题标题】:Select record by group and condition using SQL使用 SQL 按组和条件选择记录
【发布时间】:2021-08-10 15:16:03
【问题描述】:

我有一个包含客户姓名的表格。客户可以有多个名称(即多个记录绑定到同一个客户 ID),这些名称可以是不同的名称类型(即合法、首选等)。我想在存在时选择首选名称,在没有首选名称时选择合法名称。但我不太确定解决这个问题的最佳方法。

这是示例表:

ID TYPE FIRST LAST
1 PREF Johnny Smith
1 LEGAL John Smith
2 PREF Sophia Apple
3 LEGAL Tim Ritter

这是期望的结果:

ID TYPE FIRST LAST
1 PREF Johnny Smith
2 PREF Sophia Apple
3 LEGAL Tim Ritter

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    一种方法使用窗口函数:

    select t.*
    from (select t.*,
                 row_number() over (partition by id order by type desc) as seqnum
          from t
          where type in ('PREF', 'LEGAL')
         ) t
    where seqnum = 1;
    

    或者,如果每种类型的名称最多有一个,那么您可以使用:

    select t.*
    from t
    where t.type = 'PREF' or
          not exists (select 1
                      from t t2
                      where t2.id = t.id and t2.type = 'LEGAL'
                     );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2011-01-24
      • 2018-06-20
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多