Reputation: 7
I have a table named ReviewFact which has the following attributes:
- CategoryID (Primary Key)
- Star_Rating (Primary Key)
- No_of_Reviews
CategoryID refers to specific product, Star_Rating refers to a star rating given by users, No_of_Reviews refers to how many users gave this rating.
I have to write an SQL query which shows the number of 5 star reviews for each category.
I have come up with the following:
SELECT r.CategoryID, r.NUMBER_OF_REVIEWS
FROM REVIEWFACT r
WHERE r.Stars = 5
ORDER BY r.NUMBER_OF_REVIEWS desc;
Using this I get the number of reviews for rows which have 5 star reviews, but not for ones which don't. The ones which don't should have the count as 0. How do I go about solving this?
If there are the following rows in the table:
CategoryID Star_Rating No_of_Reviews
1 5 10
2 5 4
3 2 9
The query should return
CategoryID No_of_Reviews
1 10
2 4
3 0
Upvotes: 0
Views: 1525
Reputation: 94914
Group by category and sum conditionally:
select
categoryid,
sum(case when stars = 5 then no_of_reviews else 0 end) as no_of_reviews
from reviewfact
group by categoryid
order by no_of_reviews;
Upvotes: 0
Reputation: 165
Same, with IF statement:
SELECT r.CategoryID, IF(r.Stars = 5, r.NUMBER_OF_REVIEWS, 0) as bestReviews
FROM REVIEWFACT r
ORDER BY r.NUMBER_OF_REVIEWS desc;
Upvotes: 0
Reputation: 1269773
I think you just want a case
:
SELECT r.CategoryID,
(CASE WHEN r.starts = 5 THEN r.NUMBER_OF_REVIEWS ELSE 0 END)
FROM REVIEWFACT r
ORDER BY r.NUMBER_OF_REVIEWS desc;
Upvotes: 1