我想根据销售历史MySQL表列出畅销商品:
sales(id,item)
----------------
1,Chocolate
2,Chocolate
3,Flowers
将输出:
Chocolate :: 2 Sales :: 67%
Flowers :: 1 Sales :: 33%
如何使用php做到这一点?
由于
答案 0 :(得分:2)
select
name,
round(count(*)/total_row.total*100)
from
sales,
(select count(*) as total from your_tables) as total_row
group by sales.name;
答案 1 :(得分:1)
如果您拥有所有项目的数组,则可以执行类似
的操作$ary = array('Chocolate','Chocolate','Flowers');
$total = count($ary);
$count = array_count_values($ary);
foreach($count as $item=>$val) {
echo '<p>'.$item.' - '.$val.' Sales - '.($val/$total*100).'%</p>';
}
结果array_count_values是一个方便的小功能。