【问题标题】:Filter by grouping two columns通过对两列分组进行过滤
【发布时间】:2016-07-03 17:05:07
【问题描述】:
ID  Type    Status  
------------------------
1   Type1   Success 
1   Type1   Fail    
1   Type2   Fail    
2   Type3   Fail    
3   Type1   Success 

我有以上数据

我想按 Id 和 Type 过滤这个数据组

例如,如果 Id 1 和 type1 有多个记录,我只想显示此组合的一个记录(无论状态如何)。

ID  Type    Status  
------------------------
1   Type1   Success 
1   Type2   Fail    
2   Type3   Fail    
3   Type1   Success 

我尝试使用 distinct 和 group by,但没有得到正确的结果。 (此表中还有其他一些列) 这必须很简单,但我做不到。

任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server filter group-by distinct


    【解决方案1】:

    您可以为此使用ROW_NUMBER

    SELECT ID, Type, Status, ... rest of the fields here
    FROM (
      SELECT ID, Type, Status, ... rest of the fields here, 
             ROW_NUMBER() OVER (PARTITION BY ID, Type 
                                ORDER BY Status) AS rn
      FROM mytable) t
    WHERE t.rn = 1
    

    这将选择ID, Type 分区内具有最小Status 值的记录。

    【讨论】:

    • @MicrosoftDN 那么ROW_NUMBER 正是您所需要的!
    • row_number() 对我来说工作正常。感谢您的帮助
    • 接受这个作为使用ORDER BY Status的正确答案,如果我们想要该组的最新数据,我们可以在这里使用任何其他字段
    【解决方案2】:

    您可以使用聚合。如果你不关心status,就用min()

    select id, type, min(status) as status
    from t
    group by id, type;
    

    如果“不关心”真的意味着“随机”,那么请改用row_number()

    select id, type, status
    from (select t.*,
                 row_number() over (partition by id, type order by newid()) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    【讨论】:

    • @MicrosoftDN 。 . .如果您想要它们,请使用第二种解决方案。
    • row_number() 对我来说工作正常。感谢您的帮助
    猜你喜欢
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多