arg_max() / arg_min()

max() tells you the largest value in a group, but nothing else about the row it came from. arg_max() returns the row where a value is largest:

SigninLogs
| summarize arg_max(TimeGenerated, IPAddress, Location) by UserPrincipalName

Read it as: for each user, find the row with the largest TimeGenerated (the latest sign-in) and return its IPAddress and Location. arg_min() does the same for the smallest value.

The first argument is the value to maximise or minimise. After it, list the columns you want back, or write * for all of them. The output columns keep their original names, so you don’t get max_TimeGenerated; you get TimeGenerated.

Typical uses

  • The latest state of something: the last sign-in per user, the last heartbeat per device.
  • The first time something happened: arg_min(TimeGenerated, *) per device or per account.

Ties

If several rows share the largest value, arg_max() returns one of them, and which one is not defined. For timestamps that is rarely a problem; for counts or scores it can be. When it matters, make the value unique or check for ties first.

arg_max() or top? top 1 by X gives the single largest row of the whole table; arg_max(X, *) by A gives the largest row of each group.

Examples

1 The latest logon or logoff on each server, with some of its columns
SecurityEvent
| where EventID in (4624, 4634)
| summarize arg_max(TimeGenerated, EventID, TargetUserName) by Computer

The result keeps the original column names: TimeGenerated, EventID, TargetUserName.

2 The first PowerShell start on each device, all columns
DeviceProcessEvents
| where FileName == "powershell.exe"
| summarize arg_min(TimeGenerated, *) by DeviceName
| project DeviceName, TimeGenerated, ProcessCommandLine
| sort by TimeGenerated asc

* keeps every column of the earliest row; project then picks a few to show.

Practice it

None of the free exercises needs this one yet.