首页 > 解决方案 > 对具有不同值的两个字段进行分组,并按顺序选择特定值

问题描述

我一直在寻找这个问题的解决方案,但仍然找不到比这个SQL Group BY COLUMN Choose specific rows最相似的问题。

所以这是我的问题

     Type_Table
column1  |   column2
a        |   s
a        |   m
a        |   e
b        |   s
b        |   e
c        |   m
c        |   s 

所以基本上我想按column1分组,但只选择column2 = e中的值,但如果column1中的重复值不存在则选择column2 = s,但如果重复值column1中不存在则选择column2 = 米。所以结果表看起来像这样

column1  |   column2
a        |   e
b        |   e
c        |   s 

我用过这个 select column1,case when column2=e then e when column2=s then s when column2=m then m end column2 from type_table group by 1,但显然行不通。我需要的是按column1分组,对于column2中的每个不同值,如果它们各自的column1值存在则只选择e,但如果e不存在则选择s,如果s不存在则选择m。感谢您的回答

标签: sqlgoogle-bigquery

解决方案


一种方法使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by col1
                                order by (case col2 when 'e' then 1 when 's' then 2 when 'm' then 3 else 4 end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

推荐阅读