Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to SELECT the last user logged on to a computer given the Computer, User and LogonTime
    primarykey
    data
    text
    <p>If I run this query to get a list of users logged on to each computer:</p> <pre><code>SELECT T0.Computer, T4.[User], T4.[Last Modified] FROM Table1 T0 LEFT OUTER JOIN Table4 T4 ON T0.Guid = T4.Guid Where T4.[Last Modified] &gt;= getdate()-30 -- Logged in the last 30 days ORDER BY T4.[Last Modified] DESC </code></pre> <p>I get:</p> <pre><code>Computer User Last Modified -------- ----- -------------- Comp1 UserA 2013-07-14 16:31:59.000 Comp1 UserB 2013-06-03 13:43:32.000 Comp1 UserC 2013-04-28 15:58:22.000 Comp2 UserD 2013-04-28 11:10:21.000 Comp2 UserE 2013-04-19 15:01:33.000 Comp3 UserF 2013-04-18 08:01:03.000 </code></pre> <p>I would like to show the MAX([Last Modified]) to show only the last user to log on to each computer:</p> <pre><code>Computer User -------- ----- Comp1 UserA Comp2 UserD Comp3 UserF </code></pre> <p>It would make sense to say SELECT DISTINCT Computer, User ORDER BY [Last Modified] DESC But you can't use ORDER BY without specifying it in the SELECT.</p> <p>And MAX([Last Modified]) would only work if the User wasn't in the SELECT.</p> <hr> <p>Thanks @Lamak</p> <p>Is it possible to Pivot the Results to show the last two users? We could change the Row number to User1, User2, etc.:</p> <pre><code>RN = 'User' + CAST(ROW_NUMBER() OVER(PARTITION BY T0.Name ORDER BY T4.[Last Modified] DESC) AS VarChar) </code></pre> <p>Then the results could show:</p> <pre><code>Computer User1 User2 -------- ----- ----- Comp1 UserA UserB Comp2 UserD UserE Comp3 UserF NULL or '' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload