以下の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%は丸められます)。