Reputation: 3515
I have a column of DateTime type (called "FinalisedDate") in a SQL Server 2008 table. The column contains records that can be dated back a few years ago.
I need to get those rows that are falling in "the current operational data". It is defined as:
from the previous year's October 1st to May 1st of the present year if current date is before May 1st, or from the October 1st of the present year to May 1st of the next year if current date is after October 1st.
For example,
FinalisedDate
2013-04-15 00:00:00.000
2013-07-01 00:00:00.000
2013-10-01 00:00:00.000 //the current operational data
2013-11-15 00:00:00.000 //the current operational data
2013-12-30 00:00:00.000 //the current operational data
2014-01-15 00:00:00.000 //the current operational data
2014-03-01 00:00:00.000 //the current operational data
2014-04-15 00:00:00.000 //the current operational data
2014-05-30 00:00:00.000
2014-09-01 00:00:00.000
Anyone can help with a solution to get all rows of the current operational year? Thanks in advance.
Cheers, Alex
Upvotes: 0
Views: 9179
Reputation: 10918
SELECT *
FROM MyTable
CROSS APPLY (
SELECT CASE
WHEN MONTH(currentdate) < 5 THEN YEAR(currentdate)-1
WHEN MONTH(currentdate) >= 10 THEN YEAR(currentdate)
END
FROM (SELECT GETDATE()) t1(currentdate)
) t2(opyear)
WHERE FinalisedDate >= DATEFROMPARTS(opyear ,10,1)
AND FinalisedDate < DATEFROMPARTS(opyear+1, 5,1)
Upvotes: 0
Reputation: 20804
My suggestion is to take this approach. Start with two DateTime variables:
declare @StartDate as datetime, @EndDate as datetime
Then look at the current date, and use conditional logic to assign values to those variables. Then do this:
where FinalizedDate >= @StartDate
and FinalizedDate < Dateadd(day, 1, @EndDate)
You get dibs on solving the logic part on your own.
Edit starts here
However, that's a bandaid solution. You would benefit from a calendar table, ie a table with the date as the primary key and other fields as required. One of those fields would be OperationalYear and it would have values like '2013/14', '2014/15', etc.
Then you could something like this:
from thistable join CalendarTable on FinalizedDate = TheDate
where OperationalYear = (subquery that gets OperationalYear from GetDate())
Upvotes: 1
Reputation: 20330
Peronally I'd work out the date range in another function and then simply do a between query but something like
Declare @startDate DateTime
Declare @endDate DateTime
Declare @offset int
set @Offset = 0
if Month(GetDate()) < 5
begin
set @offset = -1
end
set @startDate = Convert(DateTime,Convert(VarChar(4),Year(GetDate()) - offset) + '1001',112)
set @endDate = DateSubtract(day,1,DateAdd(year,1,@startDate))
select * from MyTable Where FinalizedDate Between @startDate and @endDate
should do the job
Upvotes: 0