Search code examples
rdataframeranking

How to find Customers with Highest and second Highest sales?


I need to find out Customer Names, who made highest and second highest purchase.

Sample Data

Name   Sales
pavan  400
kumar  200
mahesh 750
rajesh 550
vasu   900

There should be two queries one for highest and one for second highest. I want only names not row.


Solution

  • Updated Answer

    R Base Solution

    Make sure the Name is Character type

    For Max

    df[which.max(df$Sales),]$Name
    #[1] "vasu"
    

    For Min

    df[which.min(df$Sales),]$Name
    #[1] "kumar"
    

    It is to note that which returns the index. So in the above case, which.max returns the index of maximum Sale Value and vice versa. Hence I am sending the index in subsetting enclosure of R.

    Second Highest

    library(dplyr)
    
    df <- df %>% arrange(desc(Sales))
    df$Name[2]
    #mahesh
    

    You can keep changing the index to get the 3rd and 4th.