我有两个表,项目和类别,示例数据如下:

Items:
Title    category_id
Item A   1
Item B   2
Item C   3
Item D   2
Item E   3
Item F   2

Categories
category_id   category
1             wood
2             plastic
3             metal

我需要做的是计算项目总数,然后列出每个类别中有多少个项目以及占总数的百分比
我知道我能数出每一个项目和总数。
select
  count(*) as total,
  sum(category_id=1) as cat_1,
  sum(category_id=2
.... etc etc

但是有没有一种方法可以做到这一切而不计算每一个类别(可能添加了新的类别,希望它继续工作),然后与categories表连接以生成名称?
理想情况下,这是我想要返回的:
Category    how many    % of total
wood        1           17%
plastic     3           50%
metal       2           33%

Total       6           100%

(17%为1/6=>16.666666 7%四舍五入)。

最佳答案

select ifnull(c.category, 'TOTAL') as Category,
    count(i.category_id) AS `how many`,
    round(count(i.category_id) / (select count(*) from Items) * 100) as `% of total`
from Categories c
left outer join Items i on c.category_id = i.category_id
where c.category is not null
group by c.category
with rollup

注意,这也将正确处理空类别。
SQL Fiddle Example
输出:
| CATEGORY | HOW MANY | % OF TOTAL |
------------------------------------
|    glass |        0 |          0 |
|    metal |        2 |         33 |
|  plastic |        3 |         50 |
|     wood |        1 |         17 |
|    TOTAL |        6 |        100 |

10-01 05:09