Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

sql - 如何使用SQL语句计算百分比(How to calculate percentage with a SQL statement)

I have a SQL Server table that contains users & their grades.

(我有一个包含用户及其等级的SQL Server表。)

For simplicity's sake, lets just say there are 2 columns - name & grade .

(为了简单起见,我们只说两列namegrade 。)

So a typical row would be Name: "John Doe", Grade:"A".

(因此,典型的行是名称:“ John Doe”,等级:“ A”。)

I'm looking for one SQL statement that will find the percentages of all possible answers.

(我正在寻找一条SQL语句,该语句将找到所有可能答案的百分比。)

(A, B, C, etc...) Also, is there a way to do this without defining all possible answers (open text field - users could enter 'pass/fail', 'none', etc...)

((A,B,C等)。此外,有没有一种方法可以定义所有可能的答案(开放文本字段-用户可以输入“通过/失败”,“无”等)。)

The final output I'm looking for is A: 5%, B: 15%, C: 40%, etc...

(我正在寻找的最终输出是A:5%,B:15%,C:40%等...)

  ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have tested the following and this does work.

(我已经测试了以下内容,这确实可行。)

The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis.

(gordyii的答案很接近,但是在错误的位置乘以100,并且缺少括号。)

Select Grade, (Count(Grade)* 100 / (Select Count(*) From MyTable)) as Score
From MyTable
Group By Grade

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...