views:

384

answers:

2

I have the following table:

ratings:

ID | post_id | rating_type

The rating_type field is either 'thumb-up' or 'thumb-down'. I want to get a result set telling me what the highest rated posts are. The following query gives me a result set with the number of up votes for each unique post_id.

SELECT COUNT(post_id) as number_up, post_id FROM wp_sp_post_ratings WHERE rating_type = 'thumb-up' GROUP BY post_id

That is great! I can do similarly for the thumb-down rating type. However, what I need is to get the total rating where each thumb-up gives a post one point and each thumb down gives a post a negative point. Then, I need to order that by the total amount of rating. So, say we have the following:

post 1 has 3 up votes and 2 down votes post 2 has 14 up votes and 33 down votes post 3 has 4 up votes and 0 down votes

I'd like to see a result set like the following:

post_id | total_rating
3 | 4
1 | 1
2 | -19

I have no idea how to do this. I've been banging my head against the documentation and Google for about 2 hours now, so I was hoping that SO could be my savior.

+3  A: 
SELECT SUM(CASE WHEN rating_type = 'up' THEN 1 WHEN rating_type = 'down' THEN -1 END CASE)
FROM posts
GROUP BY post_id

P. S. It's better to keep up and down votes as numbers (+1 and -1) rather than strings.

Quassnoi
Exactly what I needed. Thank you so much!
nickohrn
A: 

Hi!

Initially, why not store a thumbs up as 1 and a thumbs down as -1 directly? Quassnoi was quicker with the case statement....

Too late in both hints...
I would have preferred to do that, but the spec called for possible extensibility to a star rating system but not to take too much time. One of those vague requirements where you make compromises, you know?
nickohrn