Hi Vaibhav,
Thanks for quick response. I need to get list of all active users who didn't log in past 120 days. If I get list, then I should send an email to them indicating that they are inactive for pas 120 days and they will be disabled soon.
I added 2 more login row after 2 years for user 1. Your query still returns user1 and user2. It should return only User2 because he hasn't logged in 2 years. User1 logged in recently.
declare @tmpUser table
(
userid int,
username varchar(100),
startdate datetime,
enddate datetime,
StatusID int
)
declare @tmpUserLogHistory table
(
LogId int,
userid int,
reason varchar(50),
ChangeDateTime datetime
)
insert into @tmpUser
select 1, 'User1', '05-01-2017', NULL, 1
Union
select 2, 'User2', '05-05-2018', NULL, 1
Union
select 3, 'User3', '07-01-2019', '07-31-2020', 2
select * from @tmpUser
Insert into @tmpUserLogHistory
SELECT 1, 1, 'Login', '05-02-2017 12:00:00:00'
Union
Select 2, 1, 'Add instruction', '05-02-2017 12:05:00:00'
Union
select 3, 1, 'Updated stocks data', '05-02-2017 13:05:00:00'
union
SELECT 4, 1, 'Login', '05-02-2017 16:30:00:00'
Union
Select 5, 1, 'sent email to the user', '05-02-2017 16:35:00:00'
Union
SELECT 6, 2, 'Login', '05-05-2018 15:45:00:00'
Union
Select 7, 2, 'Add Check', '05-05-2018 16:00:00:00'
Union
SELECT 8, 3, 'Login', '07-05-2020 10:45:00:00'
Union
Select 9, 3, 'Contact User', '07-15-2018 16:00:00:00'
union
SELECT 10, 1, 'Login', '08-02-2020 12:00:00:00'
Union
Select 11, 1, 'Add instruction', '08-02-2020 12:05:00:00'
select * from @tmpUserLogHistory
I should get all users who are active and who didn't login in the past 120 days.
In above case User1 logged in after 2 years. So, it shouldn't pick up USER1 and Only User 2 who is active but not logged in past 120 days.
Thanks for your help