2016-02-22 59 views
1

我想獲得的收視率,在我的數據庫中的特定項目行填寫。並非所有項目都有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)是零?

Results

@霍根的回答是:

enter image description here

+0

你需要這個只有一個項目或所有項目? –

+0

我需要這一個項目,就像當你查看在谷歌Play商店的應用程序,它的額定誰1,2,3,4,5 –

+0

@GetOffMyLawn的人數 - 無法得到它的工作在mysql彙總似乎與標準的方式做到這一點混亂。 – Hogan

回答

-1

您將使用成才沿此線,以取代空值作爲0:

SELECT ISNULL(rating, 0) FROM myTable 
+1

我想他想看看他沒有的評級的行 - 沒有設置零評級爲0 – Hogan

0

這是什麼我有工作(根據@霍根的原始查詢):

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