簡體   English   中英

如何根據其他列查找一列的不同

[英]How to find the distinct of one column based on other columns

我有一個如下數據框

col1    col2    col3
A       Z       10
A       Y       8
A       Z       15
B       X       11
B       Z       7
C       Y       10
D       Z       11
D       Y       14
D       L       16

我必須為每個distinct col1選擇col2哪個有max(col3)

輸出數據框應該是,

col1    col2    col3
A       Z       15
B       X       11
C       Y       10
D       L       16

如何在RSQL執行此操作

提前致謝

我們可以使用data.table 我們將'data.frame'轉換為'data.table'( setDT(df1) ),按'col1'分組,我們根據'col3'的最大值索引對data.table( .SD )進行子集化

library(data.table)
setDT(df1)[, .SD[which.max(col3)], col1]
#     col1 col2 col3
#1:    A    Z   15
#2:    B    X   11
#3:    C    Y   10
#4:    D    L   16

或者我們可以在使用'col1'分組后使用top_ndplyr

library(dplyr)
df1 %>%
      group_by(col1) %>%
      top_n(1)

SQL答案:

如果沒有其他具有相同col1值且具有更高col3值的行,請使用NOT EXISTS返回行。

select *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.col1 = t1.col1
                    and t2.col3 > t1.col3)

如果有max(c3)平局,則返回col1的兩行。

另一種在MySQL中的做法。

這是SQLFiddle演示

輸出 :=> 在此輸入圖像描述

SELECT T1.*
FROM
table_name T1
INNER JOIN 
(SELECT col1,MAX(col3) AS Max_col3 FROM table_name GROUP BY col1) T2 
            ON T1.`col1` = T2.`col1` and T2.`Max_col3`=t1.`col3`

希望這可以幫助。

暫無
暫無

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

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