使用SQL按组计算百分比

时间:2018-07-09 20:25:06

标签: mysql sql-server

我有一个表格,其中包含学生的ID,课程名称和课程级别。

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

由此,我想知道每门课程按级别划分的百分比。

就像在下表中一样:

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

如何使用SQL做到这一点?

2 个答案:

答案 0 :(得分:1)

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 |

答案 1 :(得分:1)

使用窗口功能的另一个选择(假设2012 +)

示例

Select [Level]
      ,[Course]
      ,Pct = 100.0  / sum(1) over (partition by [Level],[Course])
  From YourTable

返回

Level   Course  Pct
1       A       50.000000
1       A       50.000000
1       B       50.000000
1       B       50.000000
2       C       100.000000