加入SQL的高级计数

时间:2012-11-01 17:23:05

标签: mysql sql

我有两张桌子,物品和类别,示例数据如下:

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%舍入)。

3 个答案:

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

<强>输出:

| CATEGORY | HOW MANY | % OF TOTAL |
------------------------------------
|    glass |        0 |          0 |
|    metal |        2 |         33 |
|  plastic |        3 |         50 |
|     wood |        1 |         17 |
|    TOTAL |        6 |        100 |

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

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