简体   繁体   中英

MS SQL Server Last User Logged in Multiple Clients with Multiple Users

I have a users table that has multiple clients with multiple users and each user has a last login date. I need to get the date of the most recent logged in user for each client. I have tried max(date) but that gets me the last login date for every user for the each client.

My goal is to get one user per client with the most recent logged in date.

 SELECT DISTINCT(u.clientid),u.userid,Max(u.lastLogin) as lastLogin
 FROM users u
 WHERE u.clientid IN (10,20,30,40)
 GROUP BY u.clientid,u.userid,u.lastLogin

 clientid  userid  lastLogin
    10        1      a date
    10        2      a date
    10        3      a date
    20        4      a date
    20        5      a date
    30        6      a date
    30        7      a date
    30        8      a date
    30        9      a date
    and so on

I'm looking for where the user is the one with the most recent login date

    clientid  userid  lastLogin
      10        1      a date
      20        4      a date
      30        6      a date
    and so on

Here a sample script using row_number() and CTE to get the user of each client having the last login please update the script according to your table sctructure and column names.

declare @mytable as table(client varchar(50),myuser varchar(50),lastlogin datetime)

insert into @mytable values
('client1','user11','2019-06-15 2:57PM'),
('client1','user12','2019-06-12 7:47PM'),
('client2','user21','2019-06-13 8:30PM'),
('client2','user22','2019-06-17 9:00AM'),
('client3','user31','2019-06-10 10:57PM'),
('client3','user32','2019-06-10 11:57PM')

;with cte as(
select client,myuser,lastlogin,row_number() over(partition by client order by lastlogin desc) r# from @mytable )
select * from cte where r#=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM