Question

I am back to a similar issue I have had previously. It should be a simple thing, but cannot get my head around it. Here is an overview of the tables and what I am trying to achieve with this subquery. I am using SQL Server 2008.

Users This contains a list of users

Login Audit Contains a list of login attempts. It holds the userID and the loginDate (datetime field)

What I am trying to achieve I want to be able to show rows of users and their last login date from the audit table.

Here is my query, that would make sense from a laymans perspective! ;-)

SELECT  u.userID, u.fName, u.sName, l.loginDate
   FROM    Users AS u LEFT OUTER JOIN
                      (SELECT    TOP (1) loginDate, userID
                        FROM   LoginAudit) AS l ON l.userID = u.userID
   WHERE   (u.cliID = 1)

This just pulls back the last loginDatefor the last user that logged in. I wanted all of the users to come back regardless if they logged in or not.

Any assistance would be appreciated.

Thanks nick

Était-ce utile?

La solution

select a.userid, a.fName, a.sName,
  max(b.loginDate)
from 
   users a 
   left outer join lastLogin b on a.userid = b.userid
group by a.userid, a.fName, a.sName

Autres conseils

You want to replace your subquery with

SELECT userID, max(loginDate) as lastLogin FROM LoginAudit GROUP BY userID

And then replace "l.loginDate" in your main query with "l.lastLogin"

The functionality you want is provided by the MAX() function in an aggregate query, not the TOP() function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top