2011-12-18 62 views
7

我想在我的儀表板前5的產品展示,每個產品我想顯示總的順序,觀點和其中該產品是基於他人前的百分比:複雜的MySQL查詢問題

Game 1 for Xbox (200 orders/1000 views) 20% 
Game 2 for WII (180 orders/2100 views) 18% 
Game 3 for PS3 (170 orders/390 views) 17% 
Game 4 for PS3 (90 orders/1400 views) 9% 
Game 5 for WII (20 orders/30 views) 2% 

因此,1000個訂單中的第1個遊戲的200個訂單佔總訂單的20%。這意味着,我的產品有20%是遊戲1

,這裏是我的查詢:

select 
products.name, products.type, products.views, count(*) as orders, ???????? 
from 
products 
inner join orders on (products.id = orders.product_id) 
group by orders.product_id 

如何獲得的百分比是多少?

+1

我不明白那部分:「意見和產品基於他人的比例」。你能更精確嗎?什麼是「意見」?什麼是「基於他人」的東西? – fge 2011-12-18 18:25:14

+0

當然我會更新我的問題 – fred 2011-12-18 18:26:29

回答

6
select 
products.name, products.type, count(*) as orders, count(*) * 100/total.total as pct 
from 
products 
inner join orders on (products.id = orders.product_id) 
inner join (select count(*) as total from orders) total 
group by orders.product_id 
+0

感謝它的工作 – fred 2011-12-18 18:40:50

+0

很好聽:) – necromancer 2011-12-18 19:52:04