2011-12-18 63 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