views:

39

answers:

2

hi

I have table that contain date and time field.

id|date|time
=========
1|01/01/2001|10:45
2|01/02/2002|11:45
3|01/03/2003|12:45
4|01/04/2004|12:55

I need to know the difference between the MAX(date) and the MIN(date)

And the MAX(time) and the MIN(time)

Something like.... MAX(date)-MIN(date) ???.....

Thanks in advance

+2  A: 

DATEDIFF is your friend.

To get the difference in number of days: SELECT DATEDIFF(day, MIN(date), MAX(date)) FROM [table] = 1186

To get the difference in number of hours: SELECT DATEDIFF(hour, MIN(time), MAX(time)) FROM [table] = 2

To get the difference in number of minutes: SELECT DATEDIFF(minute, MIN(time), MAX(time)) FROM [table] = 130

Andy Shellam
thank's for the help, if i have this format (max): 2010-03-18 10:44:00.000 and (min) 2010-01-13 03:23:00.000 - how to see the difference between ?
Gold
A: 

A very simple way to get what you are asking is ...

SELECT 
[DifferanceInMinutes] = DATEDIFF(mi,(SELECT MIN(YourDate) FROM MyTable),(SELECT MAX(YourDate) FROM MyTable))

http://msdn.microsoft.com/en-us/library/ms189794.aspx

Justin Jenkins
You don't need the subqueries - `SELECT DifferanceInMinutes = DATEDIFF(mi, MIN(YourDate), MAX(YourDate)) FROM MyTable;`
Andy Shellam
Hey, I said I really *simple* way! :)
Justin Jenkins
My way is really simple! Subqueries are more difficult to read IMO ;-)
Andy Shellam
Actually, Andy ... I agree. But when I first started at SQL it made more sense for me. I'm somewhat amazed at the number of DATEDIFF questions on Stack Overflow. Maybe they should teach it in School?
Justin Jenkins