Jump to content

sorting sum with field_name


tom_b

Recommended Posts

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 with the corresponding sum sorted desc like this

 

bob    65

jim      40

bill      30

 

I can get the sums, I can get the field names, but I can't get them into separate rows and sort them by the sums.  I've tried a number of things but I'm stumped!!!  Any ideas, hints?

 

Thanks, Tom

Link to comment
Share on other sites

Here's the query I have to get the sums. 

 

$query = 'SELECT SUM(jim) AS jim, SUM(bob) AS bob, SUM(bill) AS bill FROM week';

$result = mysql_query($query) or die(mysql_error());

 

I use this to get the field names:

 

$values['jim]['name'] = mysql_field_name($result, 0);

$values['bob']['name'] = mysql_field_name($result, 1);

$values['bill']['name'] = mysql_field_name($result, 2);

 

I can get the sums O.K. and can output them with their field names, but I can't get the sums and their corresponding field names into rows sorted descending.  Maybe different queries?  An array I don't know how to use?  Thanks for taking time.

Link to comment
Share on other sites

You can simplify your life by changing up your table structure a bit.  Consider the following:

 

counts

id    userid  count   

1      1        20   

1      2        30   

1      3        15   

2      1        20   

2      2        35   

2      3        15   

 

users

userid  username

1          jim

2          bob

3          bill

 

Now you can use the query:

 

SELECT users.name, SUM(counts.count) as totalCount 
FROM users INNER JOIN counts 
USING (userid) 
GROUP BY users.userid 
ORDER BY totalCount DESC

 

Best,

 

Patrick

Link to comment
Share on other sites

Hi!  Thank you for the idea!!  I'm new to this and this is a new idea to me but it seems to make a lot of sense, something I hadn't considered before.  In fact it might help with some other issues I've had.  I'll give it a try and let you know!!

 

Thanks, Tom

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.