0

I have an issue to get the records if the FtableID at any point in the range (Start date and End date) has a StatusID=2.

My table Structure is

ID FTableID StatusID AddedOn 75324 53591 1 2019-03-17 06:48:14.490 75325 53591 2 2019-03-18 06:48:14.663 75326 53591 3 2019-03-19 06:54:20.830

@StartDate Datetime='2019/03/17 23:00:00' ,            
@EndDate Datetime='2019/03/20 23:59:59' 

Select ID, FTableID,StatusID,AddedOn from MyTableName where FTableID=53591
And StatusID=2 and AddedOn <= @EndDate 

I know my query is wrong and it gives the record even when I pass the @startdate after its status gets changed to 3 (Completed)

I am confused to set the start date filter.

I need to check if this FtableID record is in status id =2 at any point in the range supplied

The record should come If I pass the @StartDate Datetime='2019/03/18 23:00:00', @EndDate Datetime='2019/03/20 23:59:59' because it is in this range it was in the status=2

The record should not come If I pass the @StartDate Datetime='2019/03/19 23:00:00', @EndDate Datetime='2019/03/20 23:59:59' because it was convertted to statusID=3

Please suggest me on this. Thanks in advance.

1
  • Uhm, so if you have that @StartDate variable, then why not use it in the SQL? I.e. and AddedOn >= @StartDate Or is the problem that the @StartDate is after that datetime of status 2 ? Commented Apr 16, 2019 at 7:26

2 Answers 2

0

use this

select * 
from YourTableName
where AddedOn between (@StartDate and @EndDate)
and StatusID=2
Sign up to request clarification or add additional context in comments.

Comments

0

One method uses exists.

I would simplify your date arithmetic as well, so:

declare @StartDate datetime '2019-03-17 23:00:00'; declare @EndDate datetime = '2019-03-20'

select t.*
from mytablename t
where exists (select 1
              from mytablename t2
              where t2.ftableid = t.ftableid and
                    t2.statusid = 2 and
                    t2.AddedOn >= @StartDate and
                    t2.AddedOn < @EndDate 
             );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.