我嘗試計算3個表格中項目的數量和百分比。用3個表格計算項目
表:
categories
cat_id | title
1 | phone
2 | tablet
products
prod_id | cat_id | title
1001 | 1 | iphone
1002 | 1 | nokia
1003 | 1 | blackberry
1004 | 2 | ipad
user_products
id | prod_id | user_id
1 | 1001 | 1
2 | 1001 | 2
3 | 1001 | 3
4 | 1003 | 3
5 | 1004 | 4
我到目前爲止有:
SELECT categories.cat_id, products.title, COUNT(products.title) AS cnt
FROM categories
LEFT JOIN products ON categories.cat_id = products.cat_id
GROUP BY products.title
期望的結果:
Tablets:
Ipad | 1 | 100%
Phones:
Iphone | 3 | 75%
Blackberry | 1 | 25%
你有問題要問?因爲現在你只是說明你所嘗試過的。 –
什麼是'settings_preferences'?這應該是「產品」嗎? – Barmar
@barmar謝謝!我編輯了這個問題 –