I have a table:
ComputerID, UserID, LoginDate
I need a select statement that returns:
ComputerID, UserID, LoginCount
For all computers, but for each computer, showing just the one user that logged on most often to that computer. (If there is a tie, I guess I would want to just arbitrarily pick one of the users....so this would seem to indicate I need a TOP 1 somewhere.)
(This is in ms-access, so can't use vendor specific functionality).
Solution (slight fix of JBrooks answer)
select main.*
from (select ComputerID, UserID, count(1) as cnt
from ComputerLoginHistory
group by ComputerID, UserID) as main
inner join (select ComputerID, max(cnt) As maxCnt
from
(select ComputerID, UserID, count(1) as cnt
from ComputerLoginHistory
group by ComputerID, UserID) as Counts
group by ComputerID)
as maxes
on main.ComputerID = maxes.ComputerID
and main.cnt = maxes.maxCnt
To handle the situation where >1 user may have the same loginCount for a given computer, about all I can think of to wrap another select around this, selecting the Max(UserID).....so you are basically just arbitrarily picking one of them. That's what I've done in this example, where I am pulling back the most recent user, rather than the most active user:
Select ComputerID, Max(xUserID) As UserID, MaxLoginDate
FROM
(
SELECT main.ComputerID, main.UserID as xUserID, main.MaxLoginDate
FROM [select ComputerID, UserID, Max(LoginDate) as MaxLoginDate
from ComputerLoginHistory
group by ComputerID, UserID]. AS main
INNER JOIN [select ComputerID, Max(MaxLoginDate) As MaxLogin
from
(select ComputerID, UserID, Max(LoginDate) as MaxLoginDate
from ComputerLoginHistory
group by ComputerID, UserID) as Counts
group by ComputerID]. AS maxes ON (main.MaxLoginDate = maxes.MaxLogin) AND (main.ComputerID = maxes.ComputerID)
)
GROUP BY ComputerID, MaxLoginDate
ORDER BY ComputerID