# sql - 如何使用SQL语句计算百分比

``````
From MyTable

``````
1. 最有效的( 使用 over()) 。

``````
select Grade, count(*) * 100.0 / sum(count(*)) over()
from MyTable

``````
2. 通用( 任何SQL版本) 。

``````
select Rate, count(*) * 100.0 / (select count(*) from MyTable)
from MyTable
group by Rate;

``````
3. 使用cte，最有效的。

``````
with t(Rate, RateCount) as ( select Rate, count(*) from MyTable group by Rate
)
select Rate, RateCount * 100. 0/(select sum(RateCount) from t)
from t;

``````

``````
count(*)

``````

``````
sum(count(*)) over ()

``````

``````
select Grade, 100. * count(*) / sum(count(*)) over ()
from table

``````

``````

``````

``````
with Tot(Total) ( SELECT COUNT(*) from table ) SELECT Grade, COUNT(*) / Total * 100
--, CONVERT(VARCHAR, COUNT(*) / Total * 100) + '%' -- with percentage sign
--, CONVERT(VARCHAR, ROUND(COUNT(*) / Total * 100, -2)) + '%' -- with Round from table GROUP by Grade

``````

``````
ID - Key

``````

``````
Select Grade, Count(ID) * 100.0 / ((Select Count(ID) from MyTable) * 1. 0)
From MyTable

``````

``````
declare @countOfAll decimal(18, 4)
select @countOfAll = COUNT(*) from Grades

select
Grade, COUNT(*) / @countOfAll * 100

``````

``````

``````

``````
CHAR(1) DECIMAL(32,2)
A 32. 26
B 16. 13
C 12. 90
D 12. 90
E 9. 68
F 16. 13

``````

``````
( id VARCHAR(10) not NULL, grade CHAR(1) not NULL CHECK (grade MATCHES '[ABCDEF]')
);

``````
``````

``````

``````

``````

``````

``````

``````

``````

``````
SELECT COUNT(*)
FROM myTable
INTO :TotalCount;