Skip to content
Advertisement

Group by a few columns including MAX() to limit rows but display columns not in group by

I’m outputting sp_whoisactive to a log table every 5 minutes and want to aggregate columns such as elapsed time or cpu. My best chance for unique record is session_id, login_time, login_name and I want the MAX(collection_time) for each unique record.

My question is how do you do this in one query?

I tried all kind of variations and could never get the desired output. I ended up doing 2 steps 1) the group by to a ##Temp table and 2) then joining the ##temp to the log table to get the all the columns I wanted in the report.

Step 1 query:

Step 2 query:

Advertisement

Answer

My best chance for unique record is session_id, login_time, login_name and I want the MAX(collection_time) for each unique record.

If you just want the max collection time for each tuple, then use aggregation:

On the other hand, if you want the entire corresponding rows, then one option is row_number():

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement