June 26, 2008 at 5:50 am
Hi friends,
i have column which have data like below.
6 hours
6 hours 30 minutes
''
''
''
14 hours
14 hours 30 minutes
now when i use order by it gives result like
10 hours
10 hours 30 minutes
''
''
14 hours
''
6 hours
i want it proper sorted. like 6,7,8 till 14.
ANy suggestion please?
thanks
June 26, 2008 at 6:20 am
One of the ways is to update column to have leading 0 before single digit hours. The other way is to store these values as number of minutes (smallint) and order by that field. so instead of 6 hours 30 minutes you would have 390
Piotr
...and your only reply is slàinte mhath
June 26, 2008 at 7:30 am
Yeah my idea to was to add a leading zero, that would sort it perfect!
June 26, 2008 at 7:39 am
create table source (timecol varchar(20))
insert into source values('6 hours 00 minutes');
insert into source values('6 hours 30 minutes');
insert into source values('7 hours 00 minutes');
insert into source values('7 hours 30 minutes');
insert into source values('10 hours 00 minutes');
insert into source values('10 hours 30 minutes');
insert into source values('11 hours 00 minutes');
insert into source values('11 hours 30 minutes');
select * from source order by case when len(timecol)<19 then '0'+timecol else timecol end
drop table source
June 26, 2008 at 7:45 am
HI,
try this query:
select * from source
order by Cast(Left(timecol,2) as int)
June 26, 2008 at 7:59 am
Hari.Sharma (6/26/2008)
select * from source
order by Cast(Left(timecol,2) as int)
If you add the full timecol to this then it would sort the "6 hours" and "6 hours 30 minutes" properly.
SELECT *
FROM source
ORDER BY CAST(LEFT(timecol, 2) AS Int), timecol
June 26, 2008 at 8:49 am
June 26, 2008 at 9:33 pm
Heh... that's what happens when you store dates or times as formatted data. These should be stored just as a DateTime data type and formatted for display only. Then, you wouldn't have these types of problems that will make the code horribly slow and unable to use indexes properly... best you'll ever get out of something like this is an index scan. 😉
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply