![](/img/trans.png)
[英]Average of one column based on distinct values and group by of other columns
[英]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
如何在R
或SQL
執行此操作
提前致謝
我們可以使用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_n
的dplyr
。
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中的做法。
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.