March 2, 2004 at 7:45 pm
Hi,
I'm trying to convert a datetime field to a numerical - my objective is to obtain a numerical number which I can sort on, instead of a date field.
At the moment I have select convert(int, mydate) from table
The problem is that the numerical numbering seems a little out.
eg
2004-02-27 15:44:03.000 27/02/2004 38043
2004-02-27 15:42:22.000 27/02/2004 38043
2004-02-27 15:42:03.000 27/02/2004 38043
2004-02-26 23:29:29.000 26/02/2004 38042
2004-02-26 23:33:02.000 26/02/2004 38042
2004-02-26 23:34:53.000 26/02/2004 38042
2004-02-26 23:28:00.000 26/02/2004 38042
2004-02-27 10:26:05.000 27/02/2004 38042
2004-02-27 11:08:47.000 27/02/2004 38042
2004-02-27 11:41:25.000 27/02/2004 38042
This list is sorted by numerical number descending - notice that the 27th appears below the 26th? How can I fix this?
March 2, 2004 at 8:35 pm
If you wish to drop the decimal portion (the time) of the date for the sort, use FLOOR(CONVERT(FLOAT,mydate)). If you do drop the time portion of the date, don't expect the times to be in any particular order for any given date.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 4, 2004 at 9:19 am
Another approch is to just use a "delta time" between the test date and a predefined date (e.g., '1/1/2000') [in whatever units you want] and sort on the difference value.
For example, if "seconds" will give you enough granularity, you could calculate a "DATEDIFF" delta for each date like this:
-- Determine Number of Seconds Since 1/1/2000:
DECLARE @MyTestDate DATETIME
SET @MyTestDate = '3/1/2004'
SELECT DATEDIFF(second, '1/1/2000', @MyTestDate)
Result:
131414400
and sort on the DATEDIFF values...
HTH.
- john
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply