Reputation: 593
I have to calculate date before two days based on the condition .
Example date = '2012-09-01' then @date should be '2012-08-30' but here if 2012-08-31 is not working day then @date should be '2012-08-29'.
Could you please help me on this
Upvotes: 2
Views: 283
Reputation: 4171
Your question though apparently seems to be simple, but not so as there are many test cases involved in it (at least I have interpreted in that way). Let me first write the query (I assume you are using Sql Server 2005+)
Declare @tbl_Data Table(Dates Date,WorkDayCount Int)
Insert Into @tbl_Data Select '2012-08-25',1
Insert Into @tbl_Data Select '2012-08-26',1
Insert Into @tbl_Data Select '2012-08-27',1
Insert Into @tbl_Data Select '2012-08-28',1
Insert Into @tbl_Data Select '2012-08-29',1
Insert Into @tbl_Data Select '2012-08-30',1
Insert Into @tbl_Data Select '2012-08-31',0
Insert Into @tbl_Data Select '2012-09-01',1
Declare @InputData Date = '2012-09-01'
;WITH CTE AS
(
SELECT Sequence = ROW_NUMBER() OVER(ORDER BY Dates DESC),*
FROM @tbl_Data
WHERE Dates < @InputData
)
,CTE2 AS
(
SELECT
Sequence = ROW_NUMBER() OVER(ORDER BY Dates DESC)
,Dates
,WorkDayCount
FROM
(
SELECT * FROM CTE WHERE Sequence = ((SELECT TOP 1 Sequence FROM CTE WHERE WorkDayCount = 1)-1)
UNION
SELECT TOP 2 * FROM CTE WHERE WorkDayCount = 1
)X
)
SELECT TOP 1
Date = CASE WHEN Sequence = 1 AND WorkDayCount = 0 THEN (SELECT Dates FROM CTE2 WHERE Sequence = 3)
WHEN Sequence = 1 AND WorkDayCount = 1 THEN (SELECT Dates FROM CTE2 WHERE Sequence = 2)
END
FROM CTE2
CASE 1:Input date is 1st Sept(2012-09-01) and the immediate previous date's WorkDayCount = 0
Result: 2012-08-29
Reason: Since August 31st's WorkDayCount = 0, so the working date will be 29th August
CASE 2: Input date is 1st Sept(2012-09-01) and the August 31st + August 30th WorkCount = 0.
Result: 2012-08-28
CASE 3:Input date is 1st Sept(2012-09-01) and the immediate previous date's WorkDayCount = 1
Result: 2012-08-30
Kindly correct me if any of the assumptions/test cases are incorrect.
Let me know your concern.
Upvotes: 1
Reputation: 24086
try this:
SELECT MIN(DATE_COL)
FROM (
SELECT TOP 2 DATE_COL
FROM TBL_DATE
WHERE DATE_COL<='2012-09-01'
AND WORKDAYCOUNT =1)A
Upvotes: 0