tom_b Posted February 26, 2007 Share Posted February 26, 2007 ok, I have a simple table in my DB, looks something like this: id jim bob bill 1 20 30 15 2 20 35 15 etc, what i need to do is get the sums for each column (I can do that), then output each field_name and the corresponding sum sorted desc like this bob 65 jim 40 bill 30 I've tried a number of things but I'm stumped!!! Any ideas? Thanks, Tom Quote Link to comment https://forums.phpfreaks.com/topic/40090-output-sum-field_name-sorted/ Share on other sites More sharing options...
btherl Posted February 26, 2007 Share Posted February 26, 2007 You are trying to sort the columns? SQL isn't designed for that. Instead, you can do the sorting in php after fetching the data. If you want to sort by name, then you should design your database like this: score_id name score 1 jim 20 1 bob 30 1 bill 15 2 jim 20 2 bob 35 2 bill 15 Then just do SELECT name, sum(score) FROM scores GROUP BY name ORDER BY sum(score) DESC Quote Link to comment https://forums.phpfreaks.com/topic/40090-output-sum-field_name-sorted/#findComment-193983 Share on other sites More sharing options...
tom_b Posted February 26, 2007 Author Share Posted February 26, 2007 Thanks, I'll give that a try. I've been trying to do it with PHP, I can get the data O.K., just can't seem to get the field name and sum together in one row and then sort by the sum. Maybe I can make it work this way, thanks for your time!! Tom Quote Link to comment https://forums.phpfreaks.com/topic/40090-output-sum-field_name-sorted/#findComment-194010 Share on other sites More sharing options...
btherl Posted February 26, 2007 Share Posted February 26, 2007 If you use this query and mysql_fetch_assoc, then you can use asort(): SELECT sum(jim) as jim, sum(bob) as bob, sum(bill) as bill FROM tbl Then fetch the result with mysql_fetch_assoc(), and use asort() or arsort() to sort http://www.php.net/manual/en/function.arsort.php Quote Link to comment https://forums.phpfreaks.com/topic/40090-output-sum-field_name-sorted/#findComment-194028 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.