复杂的mysql查询问题

时间:2011-12-18 18:23:05

标签: mysql

我希望在我的信息中心中显示前5个产品,在每个产品上我想显示订单总数,视图以及该产品基于其他产品的位置百分比:

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 个答案:

答案 0 :(得分: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