Query with a Custom Order

  • Hi !!

    I've a problem: is there any way to choose a custom order of the return query output that is not the same of the the table?

    I mean:

    Col1 | Val 1

    ------------------

    A | 1000

    B | 1100

    C | 120,12

    D | 20

    I need that the order return by the query is:

    Col1 | Val 1

    ------------------

    B | 1100

    A | 1000

    D | 20

    The query could be something like this:

    SELECT Col1, Val 1

    FROM Table

    WHERE Col1 in ('B','A','D')

    ORDER BY <----------:exclamation: ????????

    THANK'S

    Alex

  • ORDER BY [Val 1] DESC

    ?

    Ryan Randall

    Solutions are easy. Understanding the problem, now, that's the hard part.

  • Ah, I see [Val 1] must be a varchar, so perhaps you can make use of one of these...?

    ORDER BY LEN([Val 1]) DESC, [Val 1] DESC

    or

    ORDER BY RIGHT(SPACE(20) + [Val 1], 20) DESC

    Ryan Randall

    Solutions are easy. Understanding the problem, now, that's the hard part.

  • RyanRandall (4/21/2008)


    ORDER BY [Val 1] DESC

    ?

    Thank's Ryan !!

    But unfortunately is not what I need.... I can't order by the value order but what I have to do is to respect the same order that is in the WHERE Clause !!! :crying:

    Thank's

    Alex

  • what I have to do is to respect the same order that is in the WHERE Clause

    You can do this...

    ORDER BY CASE WHEN 'B' THEN 1 WHEN 'A' THEN 2 WHEN 'D' THEN 3 END

    Ryan Randall

    Solutions are easy. Understanding the problem, now, that's the hard part.

  • Another option and my preference is...

    DECLARE @Rows TABLE (RowNumber INT IDENTITY(1, 1), Col1 VARCHAR(10))

    INSERT @Rows SELECT 'B' UNION ALL SELECT 'A' UNION ALL SELECT 'D'

    SELECT a.Col1, a.[Val 1]

    FROM @Table a INNER JOIN @Rows b ON a.Col1 = b.Col1

    ORDER BY b.RowNumber

    Ryan Randall

    Solutions are easy. Understanding the problem, now, that's the hard part.

  • RyanRandall (4/21/2008)


    Another option and my preference is...

    DECLARE @Rows TABLE (RowNumber INT IDENTITY(1, 1), Col1 VARCHAR(10))

    INSERT @Rows SELECT 'B' UNION ALL SELECT 'A' UNION ALL SELECT 'D'

    SELECT a.Col1, a.[Val 1]

    FROM @Table a INNER JOIN @Rows b ON a.Col1 = b.Col1

    ORDER BY b.RowNumber

    Thank's Ryan!!!!!

    I'm going to try this solution !!! :w00t:

  • rossetto_ax (4/21/2008)


    RyanRandall (4/21/2008)


    Another option and my preference is...

    DECLARE @Rows TABLE (RowNumber INT IDENTITY(1, 1), Col1 VARCHAR(10))

    INSERT @Rows SELECT 'B' UNION ALL SELECT 'A' UNION ALL SELECT 'D'

    SELECT a.Col1, a.[Val 1]

    FROM @Table a INNER JOIN @Rows b ON a.Col1 = b.Col1

    ORDER BY b.RowNumber

    Thank's Ryan!!!!!

    I'm going to try this solution !!! :w00t:

    WOW !!!!

    IT WORK GREAT !!!

    THANK'S RYAN THIS IS WHAT I NEED !!

    😀

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

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