Order by Query

  • 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

  • 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

  • Yeah my idea to was to add a leading zero, that would sort it perfect!

  • 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

  • HI,

    try this query:

    select * from source

    order by Cast(Left(timecol,2) as int)

  • 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

  • Yep...

    Thats true.

    🙂

  • 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


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply