0

I have a DateTime column named EXP_Date which contains date like this :

2014-07-13 00:00:00.000

I want to compare them, like this query :

SELECT COUNT(*)
FROM DB
WHERE ('2014-07-15' - EXP_DATE)  > 1

I expect to see the number of customers who have their services expired for over a month.

I know this query wouldn't give me the correct answer, the best way was if I separate the Year / Month / Day into three columns, but isn't any other way to compare them as they are?

2
  • What datatype are you using in your table? And which version of SQL Server (2000, 2005, 2008, 2008 R2, 2012, 2014) ?? Commented Jul 15, 2014 at 13:49
  • Data Type= datetime version=2008 R2 Commented Jul 15, 2014 at 13:55

4 Answers 4

4

You can use DATEADD

 SELECT COUNT(*)
 FROM DB
 where EXP_DATE < DATEADD(month, -1, GETDATE())
Sign up to request clarification or add additional context in comments.

4 Comments

For some people it might. I like this one better.
Yup, that's just a point of view, indeed... Was just wondering if there was a specific reason ;)
what if i want to see the number of customers who have been at least 2 months expired and not more than 5 months, 2 < (exp_date - today) <5
@RmanEdv: where EXP_DATE < DATEADD(month, -2, GETDATE()) AND EXP_DATE >= DATEADD(month, -5, GETDATE())
2

Try this

 SELECT COUNT(*)
 FROM DB
 where  DATEADD(month, -1, GETDATE()) > EXP_DATE

Comments

2
 SELECT COUNT(EXPIRE)FROM 
 (Select CASE WHEN  EXP_DATE < DATEADD(month, -1, GETDATE())THEN 1 ELSE 0 END)AS EXPIRE FROM DB
  )tt

1 Comment

did you test it ? it doesn't work, this error : Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'FROM'. actually it is very useful to have that case
2

Another way using DATEDIFF


SET DATEFORMAT DMY  --I like to use "dateformat"

SELECT  COUNT(*)
FROM DB
WHERE (DATEDIFF(DAY,@EXP_DATE,GETDATE())) >= 30 --Remember, instead "Day" you can use week, month, year, etc

Syntax: DATEDIFF ( datepart , startdate , enddate ) Depart: year, quarter, month, day, week...

For more information you can visit MSDN


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.