Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

mySQL - sum.. group by.. order by

Options
  • 13-04-2006 11:24am
    #1
    Registered Users Posts: 841 ✭✭✭


    Hi,

    I have a table called gplays which records songid's and the number of plays they get on different types of jukebox:
    select songid,sum(plays) from gplays 
    group by songid order by sum(plays) desc;
    // Produces errer: Invalid use of group function
    

    The problem is with the sum() being included in the 'order by' clause. Anybody know how I can do this? Thanks


Comments

  • Registered Users Posts: 15,443 ✭✭✭✭bonkey


    I dunno MySQL too well, but in other databases the ORDER BY can contain numeric values corresponding to the columns, and can also refer to columns by their aliases.

    So the following might work:
    select   songid,
             sum(plays) as sum_of_plays
    from     gplays 
    group by songid 
    order by sum_of_plays desc;
    

    Alternately, if numeric positions are valid, you could use "order by 2 desc"

    jc


  • Registered Users Posts: 841 ✭✭✭Dr Pepper


    Spot on thanks.. Works when you use the alias but not when you try to use the function in the order by clause.. Just figured it out myself 2 minutes ago!

    Damn, that was annoying!! :D


Advertisement