根据记录SQL Server获取百分比

时间:2018-06-18 23:21:37

标签: sql sql-server tsql

问候我将此表Evaluation.Grade与这些记录一起使用:

Name Percentage
---------------
B       40
C       20
A       20
D       10
A+      10

我将评估后的给定数据存储到此表Evaluation.Assessment

Total Grade 
------------
117   A+
2     D 

我想在这里实现的是获得我存储的等级的百分比,因此我在我的代码中创建了一个限制。像这样:

Grade Percentage
------------
A+    50
D     50
A     0
B     0
C     0

但是现在使用这个查询我会得到这样的结果:

Select 
    aa.Grade, (Count(aa.Grade) * 100 / 
                    (Select Count(*) 
                     From Evaluation.Assessment 
                     Where SupervisorId = '00000000-0000-0000-0000-000000000000')) as Percentage
From 
    Evaluation.Assessment aa
Where
    aa.SupervisorId = '00000000-0000-0000-0000-000000000000'
Group By 
    Grade


 Grade Percentage
 ----------------
 A+      50
 D       50

1 个答案:

答案 0 :(得分:1)

如果我理解您的要求是正确的,那么您可以通过窗口聚合轻松实现这一目标(即使用OVER

CREATE TABLE grade 
  ( 
     NAME       VARCHAR(10), 
     percentage INT 
  ); 

CREATE TABLE assessment 
  ( 
     grade VARCHAR(10), 
     total INT 
  ); 

INSERT INTO grade 
VALUES ('B', 40), ('C', 20), ('A', 20), ('D', 10), ('A+', 10); 

INSERT INTO assessment 
VALUES ('A+', 117), ('D', 2), ('A', 65);

SELECT g.NAME                                     AS grade, 
       Count(a.total) 
         OVER( 
           partition BY a.grade) * 100 / Count(a.total) 
                                           OVER() AS percentage 
FROM   grade g 
       LEFT JOIN assessment a 
              ON g.NAME = a.grade 
ORDER  BY percentage DESC;

这就是你的结果:

enter image description here

query的在线可执行文件。