用零填写缺失的行

时间:2016-02-22 21:08:04

标签: mysql sql

我正在尝试获取数据库中特定项目的评分。并非所有商品的评级均为1,2,3,4或5;当发生这种情况时,我如何填写0的行?

因此,例如,当我的评分为1,2,3而不是4和5时,我怎么能用0填写这两行呢?

select 
rating,
count(rating) as rating_count,
(count(rating) / (select count(item_id) from ratings where item_id = 3) * 100) as percent,
avg(rating)
from ratings 
where item_id = 3
group by rating desc
with rollup

以上是上述查询的结果,因为您可以看到没有1和2的评分,如何才能获得rating_countpercentavg(rating)为0的评分?

Results

@ Hogan的回答:

enter image description here

2 个答案:

答案 0 :(得分:0)

这就是我的工作(基于@ Hogan的原始查询):

select
r_list.r as rating,
ifnull(count(rating), 0) as rating_count,
ifnull((count(rating) / (select count(item_id) from ratings where item_id = ?) * 100), 0) as percent,
ifnull(avg(rating), 0)
from (SELECT 1 AS r
UNION ALL
    SELECT 2 AS r
UNION ALL
    SELECT 3 AS r
UNION ALL
    SELECT 4 AS r
UNION ALL
    SELECT 5 AS r
) r_list
left join ratings on r_list.r = ratings.rating and item_id = ?
group by r_list.r desc
with rollup

答案 1 :(得分:-1)

您将使用沿着这一行的某些方法将空值替换为0:

SELECT ISNULL(rating, 0 ) FROM myTable