计算带有3个表的项目

时间:2014-04-21 16:54:12

标签: php mysql sql join

我尝试计算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%

3 个答案:

答案 0 :(得分:2)

SELECT c.cat_id, c.title AS cat_name, p.prod_id, p.title AS prod_name,
       COUNT(*) AS cnt,
       100*COUNT(*)/cat_total AS pct
FROM products AS p
INNER JOIN user_products AS up ON p.prod_id = up.prod_id
INNER JOIN (SELECT c.cat_id, c.title, COUNT(*) AS cat_total
             FROM categories AS c
             JOIN products AS p ON c.cat_id = p.cat_id
             JOIN user_products AS up ON up.prod_id = p.prod_id
             GROUP BY c.cat_id) AS c ON c.cat_id = p.cat_id
GROUP BY p.prod_id
ORDER BY cat_name, cnt DESC

DEMO

答案 1 :(得分:1)

试试这个

    SELECT 
    categories.cat_id, 
    products.title, 
    COUNT(user_products.id) AS cnt,
    ROUND(((
            COUNT(user_products.prod_id)/
            (
                SELECT COUNT( user_products.id )
                  FROM user_products
            INNER JOIN products ON products.prod_id = user_products.prod_id
                 WHERE products.cat_id = categories.cat_id
              GROUP BY products.cat_id
            )) * 100), 2) as percent
FROM user_products 
INNER JOIN products ON products.prod_id = user_products.prod_id
INNER JOIN categories ON categories.cat_id = products.cat_id
GROUP BY products.prod_id, categories.cat_id

答案 2 :(得分:1)

在这里你去!

SELECT  c.title AS category, p.title AS device, 
COUNT(up.prod_id) AS totalDevices,(COUNT(up.prod_id)/totNumDev)*100 AS percent 
FROM user_products AS up , products AS p , categories AS c, 

(SELECT _p.cat_id AS q2Cat, COUNT(_up.prod_id) AS totNumDev 
FROM user_products AS _up, products AS _p WHERE _p.prod_id = _up.prod_id
GROUP BY _p.cat_id) AS query2

WHERE p.prod_id = up.prod_id AND c.cat_id = p.cat_id AND query2.q2Cat = c.cat_id
GROUP BY up.prod_id;