The two common table expressions (Logins and Logouts) retrieve the change to a given RoleInstance and the change from a given RoleInstance, respectively. The first does a left join from the second to the first of subsequent records, allowing the first of the two to be null to retrieve the first logon. The second does the reverse, to retrieve the last logoff. These are then joined on the key generated by the ROW_NUMBER() function.