2

以下の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

これがあなたの最初のスタートです。これにより、最初と2番目の列が得られます。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 に答える