gpt4 book ai didi

mysql - 使用sql按组计算百分比

转载 作者:行者123 更新时间:2023-11-29 05:54:13 24 4
gpt4 key购买 nike

我有一张表,其中包含学生的 ID、类(class)名称和类(class)级别。

+----+--------+-------+   
| Id | Course | Level |
+----+--------+-------+
| 1 | A | 1 |
| 2 | A | 1 |
| 1 | B | 1 |
| 3 | B | 1 |
| 4 | C | 2 |
+----+--------+-------+

据此,我想知道每门类(class)按级别涵盖的百分比。

如下表所示:

+-------+--------+----------------+  
| Level | Course | Count_by_level |
+-------+--------+----------------+
| 1 | A | 50% |
| 1 | A | 50% |
| 1 | B | 50% |
| 1 | B | 50% |
| 2 | C | 100% |
+-------+--------+----------------+

我如何使用 SQL 执行此操作?

最佳答案

SQL DEMO

SELECT S.[Id] , S.[Course], S.[Level], T.ctotal,
100.0 / T.ctotal
FROM students S
JOIN ( SELECT [Course], COUNT(*) as ctotal
FROM students
GROUP BY [Course]
) T
ON S.[Course] = T.[Course]

输出

| Id | Course | Level | ctotal |     |
|----|--------|-------|--------|-----|
| 1 | A | 1 | 2 | 50 |
| 2 | A | 1 | 2 | 50 |
| 1 | B | 1 | 2 | 50 |
| 3 | B | 1 | 2 | 50 |
| 4 | C | 2 | 1 | 100 |

关于mysql - 使用sql按组计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253506/

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