Search code examples
maxsplunkargmax

Splunk argmax: get field value corresponding to max value of another field


Let's say on Splunk, I have a table with the fields 'month', 'year', and 'count'. I want the month corresponding to the max count for each year. So, the resulting table should only have one month per year.

I've tried using the stats and chart max functions, but I can't figure out how to use them to get what I want, or if it's even possible.

Is there any way to accomplish this using Splunk?


Solution

  • I ended up using the streamstats command.

    Given a table with fields month,year, and count,

    <some search>
    | streamstats max(count) as mc by year
    | sort +year, -count
    | streamstats first(mc) as mc
    | where count = mc
    

    Essentially, I'm using streamstats to max across each month in each year, storing a running max for each entry as a new column. Then, I sort it so that the largest max count is at the top of each year group, so that I can then select the first one as the max entry.