获得“Count(*)”的百分比为“GROUP BY”中所有项目的数量

时间:2010-06-17 12:41:43

标签: mysql

假设我需要将“特定类别中可用商品数量”的比率改为“所有商品的数量”。请考虑像这样的MySQL表:

/*

mysql> select * from Item;
+----+------------+----------+
| ID | Department | Category |
+----+------------+----------+
|  1 | Popular    | Rock     |
|  2 | Classical  | Opera    |
|  3 | Popular    | Jazz     |
|  4 | Classical  | Dance    |
|  5 | Classical  | General  |
|  6 | Classical  | Vocal    |
|  7 | Popular    | Blues    |
|  8 | Popular    | Jazz     |
|  9 | Popular    | Country  |
| 10 | Popular    | New Age  |
| 11 | Popular    | New Age  |
| 12 | Classical  | General  |
| 13 | Classical  | Dance    |
| 14 | Classical  | Opera    |
| 15 | Popular    | Blues    |
| 16 | Popular    | Blues    |
+----+------------+----------+
16 rows in set (0.03 sec)

mysql> SELECT Category, COUNT(*) AS Total
    -> FROM Item
    -> WHERE Department='Popular'
    -> GROUP BY Category;
+----------+-------+
| Category | Total |
+----------+-------+
| Blues    |     3 |
| Country  |     1 |
| Jazz     |     2 |
| New Age  |     2 |
| Rock     |     1 |
+----------+-------+
5 rows in set (0.02 sec)

*/

我需要的基本上是一个类似于这个的结果集:

/*
+----------+-------+-----------------------------+
| Category | Total | percentage to the all items | (Note that number of all available items is "9")
+----------+-------+-----------------------------+
| Blues    |     3 |                          33 | (3/9)*100
| Country  |     1 |                          11 | (1/9)*100
| Jazz     |     2 |                          22 | (2/9)*100
| New Age  |     2 |                          22 | (2/9)*100
| Rock     |     1 |                          11 | (1/9)*100
+----------+-------+-----------------------------+
5 rows in set (0.02 sec)

*/

如何在单一查询中实现此类结果集?

提前致谢。

3 个答案:

答案 0 :(得分:56)

SELECT Category, COUNT(*) AS Total , (COUNT(*) / (SELECT COUNT(*) FROM Item WHERE Department='Popular')) * 100 AS 'Percentage to all items', 
FROM Item
WHERE Department='Popular'
GROUP BY Category;

我不确定MySql语法,但您可以使用子查询,如图所示。

答案 1 :(得分:9)

这应该这样做:

SELECT I.category AS category, COUNT(*) AS items, COUNT(*) / T.total * 100 AS percent
FROM Item as I,
     (SELECT COUNT(*) AS total FROM Item WHERE Department='Popular') AS T
WHERE Department='Popular'
GROUP BY category;

答案 2 :(得分:2)

SET @total=0;

SELECT Category, count(*) as Count, count(*) / @total * 100 AS Percent FROM (
    SELECT Category, @total := @total + 1
    FROM Item
    WHERE Department='Popular') temp
GROUP BY Category;

这样做的一个好处是你不必复制WHERE条件,这是一个滴答作响的定时炸弹,下次有人来更新条件,但没有意识到它是两个不同的地方。

如果WHERE更复杂(有多个连接等),避免重复的WHERE条件也会提高可读性,尤其是