簡體   English   中英

通過分組兩列進行過濾

[英]Filter by grouping two columns

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

我有上述數據

我想按ID和類型過濾此數據組

例如,如果Id 1和type1有多個記錄,我只想顯示此組合的一個記錄(與狀態無關)。

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

我嘗試使用distinct和group by,但沒有得到正確的結果。 (此表中還有其他一些列)此musu非常簡單,但我無法做到。

任何幫助,將不勝感激。

您可以使用聚合。 如果您不關心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;

您可以為此使用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值最小的記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM