You don't mention where the field department comes from (the csv file or the events), so I'm going to assume it's in the csv file. This will need some slight adjustment if department is in the base events.
index=unix_security
[| inputlookup accounts.csv
| fields userid
| eval userid=userid."@*"]
| stats latest(_time) AS last_login BY userid
| rex field=userid "^(?<userid>[^@]+)"
| append [| inputlookup accounts.csv | eval last_login=0 ]
| stats max(last_login) AS last_login, latest(username) AS name, latest(department) AS department BY userid
| sort - userid
As you mentioned that you're still learning, I'll walk through it, chunk by chunk. First, we gather events relating only to the users in the csv by using a subsearch to gather the userid values and adding "@*" to the end of each one, as you mentioned that the raw events contain the full email address but the csv file contains the username (portion of the email before the @ sign). If all the userids belong to the same domain, you might replace "@*" with "@yourdomain.com" or whatnot.
index=unix_security
[| inputlookup accounts.csv
| fields userid
| eval userid=userid."@*"]
After that, I replaced your dedup command with this stats call:
| stats latest(_time) AS last_login BY userid
This more efficiently returns the latest value of _time for each userid, which also dedups the results. I next truncate the userid values from the raw events:
| rex field=userid "^(?<userid>[^@]+)"
Then I append in the whole list from the csv, and add last_login=0 to each user so that this call:
| stats max(last_login) AS last_login, latest(username) AS name, latest(department) AS department BY userid
can either preserve the 0 (if the user was not seen in the raw events) or carry through the last_login value from the events. This also preserves the username and department if they were in the csv. If you need to extract them from the raw events, you'll need to add latest(username) AS name, latest(department) AS department to the first stats call, as well. Finally, I preserve the sorting you intended:
| sort - userid
I hope this is helpful!
... View more