select * from Item; +----+------------+---6ren">
gpt4 book ai didi

mysql - 获取 "Count(*)"占 "GROUP BY"中所有项目数的百分比

转载 作者:行者123 更新时间:2023-11-29 18:42:26 29 4
gpt4 key购买 nike

假设我需要“特定类别中可用的项目数量”与“所有项目的数量”的比率。请考虑这样的 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)

*/

如何在单个查询中获得这样的结果集?

提前致谢。

最佳答案

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 语法,但您可以使用子查询,如图所示。

关于mysql - 获取 "Count(*)"占 "GROUP BY"中所有项目数的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44866292/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com