SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    ORDER BY with added calculation

    SELECT field1 FROM table1 ORDER BY field2, field3

    However I need to add something in so it also orders by a value that is returned from a calculation:

    SELECT field1 FROM table1 ORDER BY field2, (if field 4=="" and field 5==1 then order these records in order), field3

    So they are ordered by field2, then the calculation, then field3

  2. #2
    SitePoint Wizard webcosmo's Avatar
    Join Date
    Oct 2007
    Location
    Boston, MA
    Posts
    1,480
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    SELECT field1 FROM table1 ORDER BY field2, CASE WHEN @a=1 Then UserName Else FirstName END
    , field3

    @a is an example variable here.

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,341
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by johnsmith153 View Post
    SELECT field1 FROM table1 ORDER BY field2, (if field 4=="" and field 5==1 then order these records in order), field3
    what if field4 isn't empty, or field 5 isn't 1? what then?
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks webcosmo, I managed to work it out from this.

    SELECT field1 FROM table1 ORDER BY field2, CASE WHEN field4='"" && field5=1 THEN 1 ELSE 0 END, field3


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •