我有一个包含用户及其等级的 SQL Server 表。为了简单起见,我们假设有两列 - name
和 grade
。因此,典型的行是姓名:“John Doe”,成绩:“A”。
我正在寻找一个 SQL 语句,它可以找到所有可能答案的百分比。 (A、B、C 等...)此外,有没有一种方法可以在不定义所有可能答案的情况下执行此操作(打开文本字段 - 用户可以输入“通过/失败”、“无”等...)
我正在寻找的最终输出是A:5%,B:15%,C:40%,等等...
最佳答案
最有效(使用 over())。
select Grade, count(*) * 100.0 / sum(count(*)) over() from MyTable group by Grade
通用(任何 SQL 版本)。
select Grade, count(*) * 100.0 / (select count(*) from MyTable) from MyTable group by Grade;
对于 CTE,效率最低。
with t(Grade, GradeCount) as ( select Grade, count(*) from MyTable group by Grade ) select Grade, GradeCount * 100.0/(select sum(GradeCount) from t) from t;
关于sql - 如何用SQL语句计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770579/