简体   繁体   中英

How to get count of occurrence of specific value for each row SQL

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

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;

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM