Dynamic Order By

  • Dear All,

    I have a set of rows, a sample listed below

    IDStatus PageID

    110

    2112

    3215

    440

    500

    6413

    700

    8415

    920

    Now I wish to list the rows in Status ASC order, however, only those rows that have the Page ID > 0 will be ordered.

    How can i achieve that?

    I tried something like

    ORDER BY CASE pageID > 0 THEN Status ASC

    However I have a syntax error

    Thanks for your help and time

    Johann

  • What will happen to the rows that aren't ordered? Please show us how your result set should look.

    John

  • The rows that are not ordered, will be listed after the ordered rows

    So the resultset should look something like this:-

    ID Status PageID

    2 1 12

    3 2 15

    6 4 13

    8 4 15

    4 4 0

    5 0 0

    7 0 0

    9 2 0

    1 1 0

  • try the following -

    select Id, Status, PageId from YourTable

    order by case when PageId > 0 then Status End

    http://rajanjohn.blogspot.com

  • I clarified with my project leader

    this is enough

    ORDER BY PageID DESC, Status ASC

  • thanks for your help guys

  • but there you cant change the "> 0" to any other value, say "> 5". Or, is the PageId value not an issue?

  • Seems like the important thing is that the PageID > 0, that is why I am ordering in

    ORDER BY PageID DESC, Status ASC

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

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