2

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

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

但是有没有办法在不计算每一个的情况下完成这一切(可能添加了新的类别并希望它继续工作),然后加入类别表以产生名称?

理想情况下,这是我想要返回的:

Category    how many    % of total
wood        1           17%
plastic     3           50%
metal       2           33%

Total       6           100%

(17% 是 1/6 => 16.666666667% 四舍五入)。

4

3 回答 3

5
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 小提琴示例

输出:

| CATEGORY | HOW MANY | % OF TOTAL |
------------------------------------
|    glass |        0 |          0 |
|    metal |        2 |         33 |
|  plastic |        3 |         50 |
|     wood |        1 |         17 |
|    TOTAL |        6 |        100 |
于 2012-11-01T17:30:17.033 回答
0

这是你的初步开始。这将为您提供第一列和第二列。要获得 3 列,您将需要进行一些计算。

select c.Category, Count(Category_id)
from dbo.Items i
INNER JOIN dbo.Categories c
    ON i.Category_Id = c.Category_ID
GROUP BY c.Category
于 2012-11-01T17:33:28.340 回答
0

这种交叉连接的计数方式将考虑具有零项的类别:

select c.Category
    , (select count(*) from Items where category_id = c.category_id) as HowMany
    , (select count(*) from Items where category_id = c.category_id)
        / (select count(*) from Items) * 100
        as PctOfTotal
from Categories as c;
于 2012-11-01T17:34:46.450 回答