My table rating
is having the following structure:
RATING (INT 'id', INT 'stars') primary key 'id';
It is already known that stars
can have value from 1 to 5 only.
Below are some possible content of my table:
Sample Table1:
ID Stars
-- -----
1 5
2 4
3 4
4 4
5 5
6 4
7 4
Sample Table2:
ID Stars
-- -----
1 1
2 2
3 3
4 2
5 1
6 1
7 1
8 2
开发者_开发问答9 1
I am querying my table with the following query:
SELECT stars, count(stars) as count
FROM rating
GROUP BY stars
ORDER BY stars desc;
Sample Table1 Output:
stars count
----- -----
5 2
4 5
Sample Table2 Output:
stars count
----- -----
3 1
2 3
1 5
My Problem: I want such a query where the output is shown ZERO for the value which is not present in the table i.e.
For Sample table1 I want output like:
stars count
----- -----
5 2
4 5
3 0
2 0
1 0
For Sample Table2 I want output like:
stars count
----- -----
5 0
4 0
3 1
2 3
1 5
Please note that it is known that stars
can have only values from 1 to 5.
The query I am trying is (not working correctly):
SELECT stars, count(stars) as count
FROM rating
WHERE stars in (1,2,3,4,5)
GROUP BY stars
ORDER BY stars desc;
Is the problem with the where clause?
select s.stars, count(r.stars) as count
from
(
select 1 as stars
union all select 2
union all select 3
union all select 4
union all select 5
) s
left join rating r on s.stars = r.stars
group by s.stars
order by s.stars desc
Something like this
SELECT s.id, count(r.stars) as starcount
FROM rating r
RIGHT JOIN (SELECT 1 as id UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) s
ON (s.id = r.stars)
GROUP BY s.id
ORDER BY s.id desc;
精彩评论