Question

I have a table called Login. I want to get the No. of days from the last login per user
See sample data below:

tableName: Login    
ID|UserName|LoginDateTime  
1 |User1   |04/09/12 18:07:06  
2 |User1   |04/09/12 18:07:51  
3 |User1   |04/09/12 18:21:41  
4 |Admin   |17/09/12 15:36:30  
5 |Admin   |17/09/12 15:36:30  

Here is my SQL command:

SELECT LoginDateTime, UserName,(DATEDIFF (DAY, [LoginDateTime], GETDATE ())) 
AS [datediff] 
FROM Login;

Result:

ID|UserName|LoginDateTime    |No. of Days  
1 |User1   |04/09/12 18:07:06|414  
2 |User1   |04/09/12 18:07:51|414  
3 |User1   |04/09/12 18:21:41|414  
4 |Admin   |17/09/12 15:36:30|401  
5 |Admin   |17/09/12 15:36:30|401 

But I want to remove the duplicate records

ID|UserName|LoginDateTime    |No. of Days   
1 |User1   |04/09/12 18:07:06|414  
2 |Admin   |17/09/12 15:36:30|401  

Appreciate any help.

Was it helpful?

Solution

Try this, if you want to get the latest login for each user.

SELECT UserName, MAX([LoginDateTime]) AS LoginDateTime,
   (DATEDIFF (DAY, MAX([LoginDateTime]), GETDATE ())) as [datediff]
FROM Login
GROUP BY UserName

The idea is to use GROUP BY to group all your rows by Username, and Using MAX aggregate function get only the row with the latest LoginDateTime, then calculate the number of days using that latest loginDateTime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top