homepage Welcome to WebmasterWorld Guest from 54.226.173.169
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
MySQL ORDER BY in conjunction with a SUM field
need to know how to represent SUM as either 1 or 0
jdbnd




msg:4022131
 2:18 am on Nov 10, 2009 (gmt 0)

I have a sum(featured_program) function in a query on my website that sums the values in the featured_program field, which are all 1s and 0s.

What I would like to do is order the results by whether the sum(featured_program) field equals 0, or something greater than 0 - i.e., I believe, cast or convert the sum(featured_program) field as a boolean.

How do I do this? Have been trying to use "ORDER BY (CAST(sum(featured_program)) as BOOL) DESC" but keep getting errors.

Thanks!

 

TheMadScientist




msg:4022163
 3:30 am on Nov 10, 2009 (gmt 0)

I don't remember off the top of my head for SUM(), but with COUNT() you can (simplified):

"SELECT COUNT(col) AS total WHERE something='stuff' ORDER BY total";

The key is using the alias for the ORDER BY...
I would try:

"SELECT SUM(col) AS total WHERE something='stuff' ORDER BY total";

Then refer to the manual if you don't get it. Like I said, I don't remember if this works with SUM() off the top of my head or not.

jdbnd




msg:4022166
 3:49 am on Nov 10, 2009 (gmt 0)

Thanks, but wouldn't this just order it by the value in sum(featured_program)?

Let's say I had the following data:

id ¦ name ¦ sum(featured_program)
1 ¦ one ¦ 0
2 ¦ two ¦ 8
3 ¦ three ¦ 4
4 ¦ four ¦ 1
5 ¦ five ¦ 0

Let's say I order by sum(featured_program) DESC then name ASC. That would put #2 first, which is not what I want to do. I want to put #4 first, by treating all rows where sum(featured_program)>0 equally, for sorting purposes. Make sense? Am I misreading your reply?

Thanks!

TheMadScientist




msg:4022181
 4:21 am on Nov 10, 2009 (gmt 0)

Something like this is closer to what you are looking for then (I think):

"SELECT id,name,SUM(featured_program) AS total GROUP BY name HAVING featured_program>0 ORDER BY total";

Completely untested, but very similar to something I use with a COUNT()... Hope it gives you some ideas or a direction to go.

You might have to edit the GROUP BY or cols selected depending on your situation...

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved