SQL查询:WHERE子句

3

我的表 rating 具有以下结构:

RATING (INT 'id', INT 'stars') primary key 'id';

已知 stars 只能取值为 1 到 5。

下面是我的表的一些可能内容:

样例表格1:

ID  Stars
--  -----
1   5
2   4
3   4
4   4
5   5
6   4
7   4

示例表2:

ID  Stars
--  -----
1   1
2   2
3   3
4   2
5   1
6   1
7   1
8   2
9   1

我正在使用以下查询语句查询我的数据表:

SELECT stars, count(stars) as count
FROM rating
GROUP BY stars
ORDER BY stars desc;

示例表格1输出:

stars  count
-----  -----
5      2
4      5

样例表格2输出:

stars  count
-----  -----
3      1
2      3
1      5

我的问题: 我想要这样一条查询语句,其中对于表中不存在的值,输出应该显示ZERO

对于示例表1,我想要如下输出:

stars  count
-----  -----
5      2
4      5
3      0
2      0
1      0

我想要类似于样例表格2的输出结果:

stars  count
-----  -----
5      0
4      0
3      1
2      3
1      5

请注意,已知stars的值只能在1到5之间。
我尝试的查询(未正确工作):
SELECT stars, count(stars) as count
FROM rating
WHERE stars in (1,2,3,4,5)
GROUP BY stars
ORDER BY stars desc;

问题出在where子句吗?

2个回答

3

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

类似这样的


1
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;

嗨Johan:它显示以下错误输出。 Stars:5,4,null,null,nullCount:2,5,0,0,0 - sumit
1
@iSumitG,请确保您正在执行的是 select s.id ... 而不是 select r.stars, .... - Johan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接