Jump to content

[SOLVED] Only show rows with a group sum of greater than zero?


Recommended Posts

The code below works fine.

 

select distinct(u.userid), u.*, sum(e.amount) as amnt from `users` as u left join `earnings` as e on u.userid = e.referral where u.referrer = '$userid' group by u.userid ORDER BY amnt DESC LIMIT $from, $max_results

 

Now, if I want to ONLY display rows where amnt is GREATER THAN zero, it doesn't work. How can I make it a statement on a column that was just created from a sum?

 

This doesn't work:

 

select distinct(u.userid), u.*, sum(e.amount) as amnt from `users` as u left join `earnings` as e on u.userid = e.referral where u.referrer = '$userid' and amnt > 0 group by u.userid ORDER BY amnt DESC LIMIT $from, $max_results

 

This seems like a really simple problem but I can't figure it out.

 

Ok, but that doesn't fix my problem. I'm trying to only show rows where the amnt column is greater than zero but it's not working because the amnt column really isn't a physical column, just one that I made up on the fly from a sum. How can I make it work?

J, what the code does so far is it adds up all the users earnings from the database and then puts their totals into a new separate column called "amnt".

 

For instance, if Joe has 5 rows in the earnings table where each dollar value from the "amount" column sums up to $10.00, then by doing this code, it will distinctively display Joe one time, and then the new "amnt" column will show Joe's total sum of money. What I am trying to do is display ONLY the rows where "amnt" is greater than zero. The strange thing is that you can order by the temp amnt column, but you cannot create a "where" clause with it for some reason. There has to be a way.

I understand now.  I haven't tested this, but you'll want to look at the HAVING clause:

 

select distinct(u.userid), u.*, sum(e.amount) as amnt from `users` as u left join `earnings` as e on u.userid = e.referral where u.referrer = '$userid' and amnt > 0 group by u.userid HAVING amnt > 0 DESC LIMIT $from, $max_results

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.