I am currently creating SQl where I need to find DateDiff between two Dates.
My sample Table
Sno ItemId LineItemId CurrentEndDate RStartDate REndDate
1 101 541 10/12/2013 11/12/2013 10/12/2014
2 101 542 10/01/2014 10/01/2014 12/12/2014
3 101 543 09/01/2014 11/01/2014 10/01/2016
4 102 544 10/12/2013 11/12/2013 10/12/2014
5 102 589 10/12/2013 11/12/2013 10/12/2014
I have following conditions:
- CurrentEndDate should be btw Today-30 AND Today+365.
- Difference between RstartDate & REndDate should be more than year(365).
If All condition satisfy for each ItemId then I will Display Valid Else Not Valid.
Note: All the Rows should satisfy the above conditions.
I wrote a SQL and unable to find a proper way in getting DateDiff for RstartDate & REndDate.
OutPut:
Expected Result :
ItemId Result
101 NotValid
102 Valid
But Getting following Result :
ItemId Result
101 Valid
101 NotValid
102 Valid
SQL
Select ItemId,
Case:
(Cast(DATEDIFF(DAY,MIN(CurrentEndDate) OVER(PARTITION BY ITemId),GETDATE()) AS int) < 30
AND Cast(DATEDIFF(DAY,MIN(CurrentEndDate) OVER(PARTITION BY ITemId),GETDATE()) AS int) > -365)
AND (Cast(DATEDIFF(DAY,MAX(CurrentEndDate) OVER(PARTITION BY ITemId),GETDATE()) AS int) < 30
AND Cast(DATEDIFF(DAY,MAX(CurrentEndDate) OVER(PARTITION BY ITemId),GETDATE()) AS int) > -365)
AND CAST(DATEDIFF(DAY,RStartDate,REndDate) + 1 AS int) >= 365
THEN 'QUOTED'
else 'Not Valid'
End As Result
From ItemTable
Explanation:
- For CurrentEndDate I Found Max & Min for each ItemId and Applied the condition 1. Thinking if Max and Min satisfy the Rest of the in between rows would also satisfy.
- But I am not sure how to apply DateDiff for Rstartdate & RendDate. Since I need to Apply condition 2 for each row individually..
Note: For Row 2 the Difference btw RstartDate and REndDate is not more than 365.
Please help...