Refine SQL date-range query - sql-server

Attempting to query for when, given parameters #startDate and #endDate, a record occurs in as much of the time frame as is supplied. I have a functional where clause below, but I suspect it can be more direct.
If an end date is supplied, records will not be selected from after that date. If a start date is supplied, records will not be selected from before that date. If no dates are supplied all records will be selected.
SELECT *
FROM myTable
WHERE
(
(#startDate IS NULL AND ((#endDate IS NULL) OR (myTable.[recordDate] <= #endDate)))
OR
(#endDate IS NULL AND ((#startDate IS NULL) OR (myTable.[recordDate] >= #startDate)))
OR
(myTable.[recordDate] BETWEEN #startDate AND #endDate)
)

You could workaround with ISNULL function like below:
SELECT * FROM myTable
WHERE myTable.[recordDate] >= ISNULL(#startDate, '01/01/1900')
AND myTable.[recordDate] <= ISNULL(#endDate, getDate())
This query will select all the rows that are either:
Between #startDate and #endDate inclusive of both
Between #startDate and current date time if #endDate is null
Between 01/01/1900 if #startDate is null and todays' date time if #endDate is null
Between 01/01/1900 if #startDate is null and #endDate

Setup a temp tableceiling with floor and ceiling and join to table on date BETWEEN floor and ceiling. Setup your unbounded conditions(NULL)as 1/1/1900 and 12/31/9999. A colleague showed me this recently and it worked.

Related

How to get data between start and endate and also data must be greater than 2018 in SQL Server

I want to fetch data between start and end dates and also only the data which is greater than year 2018.
Example:
if Startdate = 2016-01-01,
Enddate = 2018-03-01
I need to fetch data only from 2018-01-01 to 2018-03-01.
How to do this in SQL Server?
I'll assume you're using #Startdate and #Enddate as parameters.
The easiest way is just include the additional criterion in the WHERE clause.
SELECT *
FROM mytable mt
WHERE mt.startdate >= #Startdate
and mt.enddate <= #Enddate
and mt.startdate >= '20180101';
This is one of those queries though, that when you see it again in 6 months, you'll ask who the heck wrote that crap (before you realise it was you).
While the above is accurate, a more pleasing version (where the logic is much easier to see) is to modify the #Startdate first
IF #Startdate < '20180101' SET #Startdate = '20180101';
SELECT *
FROM mytable mt
WHERE mt.startdate >= #Startdate
and mt.enddate <= #Enddate;
So, if #startDate and #endDate are parameters. You have to add a AND in order to check if startDate is greater than your base date (2018)
you can also replace the '2018-01-01' with an #baseDate parameter
SELECT
*
FROM
yourTable
WHERE
yourTable.startDate > #startDate
AND yourTable.startDate > '2018-01-01'
AND yourTable.endDate < #endDate

Date range Parameters in SSRS. Passing same date value to #StartDate and #EndDate is not returning any data

SSRS Report having Data Range Parameters StartDate and EndDate pointing to DateTime column which is in format 2020-07-05 08:00:00.287
When I select Same Date say 10/05/2020 in StartDate and EndDate expecting record for that single daye but it's not returning/displaying any data. where as I check and see there's data available in the table.
Current Query:
Select * from Table1
Where [DateTime]>=#StartDate AND [DateTime]<=EndDate
Also tried BETWEEN and (CONVERT(VARCHAR(20),DateTime,101), didn't work.
I want to use StartDate and EndDate as date range parameters and if I select same date(Single date) for both the Parameters it should return data from that Date.
Appreciate any leads on resolving this issue.
Use the DATEADD Function to Increment by 1 Day and Then Compare
In this scenario where the underlying data in the transactional date column is a DATETIME value, I would just increment the parameter by 1 and create a less than condition as follows:
DECLARE #StartDate AS DATE
DECLARE #EndDate AS DATE
SET #StartDate = CAST(GETDATE() AS DATE)
SET #EndDate = CAST(GETDATE() AS DATE)
;
SELECT
*
FROM
favorite_table
WHERE
1 = 1
AND transactional_dt >= #StartDate
AND transactional_dt < DATEADD(d,1,#EndDate );

Exclude in between dates

I have 2 dates #StartDate and #EndDate, I have a table in which I have stored shift dates of specific employees structure is defined below like this.
EmpCode ShiftCode StartDate EndDate
1 24 2019-10-01 2019-10-12
1 26 2019-10-13 2019-10-20
If I provide #startDate = '2019-10-01' and #endDate = '2019-10-15'
It should not get the following data, I want to exclude the rows where dates are in between the provided dates.
If the parameters provided are lets say are '2019-10-21' and '2019-10-31' respectively then it's should give me the employee code as its shift is not defined in these dates and I can add it.
This is what I have tried so far but it's not returning the desired result.
SELECT
EmpCode
FROM
TABLE
WHERE
[Roster].[EndDate] NOT BETWEEN #startDate AND #endDate OR
[Roster].[EndDate] NOT BETWEEN #startDate AND #endDate
As Shikar has deleted his post, the simple solution would be...
...
WHERE
#startDate NOT BETWEEN [Roster].[StartDate] AND [Roster].[EndDate] AND
#endDate NOT BETWEEN [Roster].[StartDate] AND [Roster].[EndDate]
You can achieve this by changing the 'NOT's position. Also you did have a copy paste error on your where clause.
SELECT
EmpCode
FROM
TABLE
WHERE
NOT (
[Roster].[StartDate] BETWEEN #startDate AND #endDate AND
[Roster].[EndDate] BETWEEN #startDate AND #endDate
)

Date parameters returning values outside the range of dates

Using SQL Server Management Studio, I have a query that I'm using date parameters but when I execute the query, I see rows that aren't in the date range selected.
DECLARE #StartDate Date = '7/10/2017'
DECLARE #EndDate Date = '7/17/2017'
SELECT DISTINCT
PROJECTID,
ACTIVITYID, ACTIVITYNAME,
ISPRIMARYRESOURCE, RESOURCEID,
STARTDATE, FINISHDATE,
FORMAT(STARTDATE,'dddd') + ', ' + FORMAT(STARTDATE,'m') + ', ' +
FORMAT(STARTDATE,'yyyy') AS ES_FORMATTED
FROM
Primavera_ODS.TASKRSRCX
WHERE
PROJECTID IN ('ONLINE', 'ESR01', 'H-ONL-Active', 'HNP-NBKRRPLD', 'HNP-RVH-LIV',
'HNP-CSCR-LIV', 'HNP-TCS-LIV', 'HNP-LPT-LIV', 'HNP-DICSP-LIV',
'HNP-NRRVHE', 'HNP-IDS-LIV')
AND FINISHDATE >= #StartDate
AND STARTDATE < #EndDate
ORDER BY
STARTDATE
The STARTDATE and FINISHDATE fields are formatted as datetime.
When the query is executed, the first row is showing a STARTDATE of 2012-11-01 08:00:00.000 and a FINISHDATE of 2018-09-27 17:00:00.000. Clearly not in the date range declared.
What am I doing wrong?
DECLARE #StartDate Date = '7/10/2017'
Is this 7th October 2017 or 10th July 2017?
Either way
FINISHDATE >=#StartDate and STARTDATE < #EndDate
means
'2018-09-27' >= '2017-07-10' AND '2012-11-01' < '2017-07-17'
Both conditions are true
Do you mean this?
STARTDATE < #StartDate AND #EndDate <= FINISHDATE
You need to test both dates lie within the bounds so:
#StartDate BETWEEN STARTDATE AND FINISHDATE
AND
#EndDate BETWEEN STARTDATE AND FINISHDATE
You may also need:
AND
#StartDate < #EndDate
You can also write your dates as '17-July-2017' or '2017-07-17' to avoid any ambiguity.
If your SQL is as per above, then nothing is wrong.
Your criteria is that FINISHDATE >= #StartDate and #StartDate is '7/10/2017'. From the result you get of FINISHDATE = '2018-09-27 17:00:00.000', so clearly FINISHDATE > #startDate.
The criteria also say that STARTDATE < #EndDate. #EndDate is set to '7/17/2017' and you get back STARTDATE = '2012-11-01 08:00:00.000 ', which is true.
My assumption is that your date range should be between #StartDate and #EndDate? If that is correct maybe you could try something like:
AND
FINISHDATE BETWEEN #StartDate AND #EndDate
AND
STARTDATE BETWEEN #StartDate AND #EndDate
Niels
You were exactly right gbn. I've accepted the query parameter and results were returning the data as requested.

TSQL Search Query between two dates

I am having a little trouble figuring out how to write a query that seems pretty straight forward.
The problem is in my WHERE clause. There are two fields in my table. A timestamp for when the task has started startTime and a timestamp for when the task was completed endTime/ Both of these fields are Datetime.
In my UI, I allow the person to select a Start Date and End Date and their filtering option.
The date logic should be as follows:
Everything where the StartTime is >= #startDate but < #endDate and the EndTime is <=#endDate but > #startDate.
I have done date ranges before using a single date in the database but not multiple so I am confused.
Any thoughts?
-- Fetch our data
SELECT [recordID],
[ItemID],
[QID],
[NTID],
[EmpID],
[FirstName],
[LastName],
[SupQID],
[SupEmpID],
[SupFirstName],
[SupLastName],
[Location],
[Department],
[Skillset],
[BudgetMarket],
CONVERT (VARCHAR (20), [startTime], 100) AS startTime,
CONVERT (VARCHAR (20), [endTime], 100) AS endTime,
COALESCE (DATEDIFF(SECOND, startTime, endTime), 0) AS totalTimeSeconds
FROM itemTracker_records
WHERE (#employee IS NULL OR (QID = #employee))
AND (#supervisor IS NULL OR (supQID = #supervisor))
AND CAST(endTime as Date) >= #startDate AND CAST(endTime as Date) < #endDate
FOR XML PATH ('results'), TYPE, ELEMENTS, ROOT ('root');
Shouldn't it be as simple as :
WHERE (StartTime >= #startDate AND #startDate < #endDate )
AND (EndTime <= #endDate AND #endDate > #startDate)
Or, slightly shorter:
WHERE StartTime between #startDate AND #endDate
AND EndTime between #startDate AND #endDate
Assuming "good" data, i.e. tasks always end after they start and the user supplied range is valid:
where startTime >= #StartDate and endTime <= #EndDate
As long as that is true then the task time span must be contained within the user specified range.
Note that a common problem is attempting to find date/time values between a pair of dates. To include all times on the last day it is necessary to add one day to #EndDate and remove equality from the comparison.

Resources