SQL:完成百分比

时间:2019-03-13 16:01:24

标签: sql

我需要有一个SQL查询来计算按位置(是不同的SQL表)完成的课程的百分比。

  

课程表的状态为“ C”(已完成状态)。

select Locations.Name, ( ??? ) as PercentCompleted
from Locations inner join Candidates ON Locations.Id = Candidates.SpecifiedLocation
inner join Courses on Candidates.Id = Courses.CandidateId
Group By Locations.Name

我希望结果是:

Location   PercentCompleted
Loc1         10
Loc2         50
Loc3         75

其中10、50和75是每个位置完成课程的百分比。

这可以通过单个SQL查询来实现吗?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,我认为你可以做到:

select l.Name,
       avg(case when co.status = 'C' then 100.0 else 0 end) as PercentCompleted
from Locations l inner join
     Candidates c
     on l.Id = c.SpecifiedLocation inner join
     Courses co
     on c.Id = co.CandidateId
group by l.name;

答案 1 :(得分:0)

尝试如下

select Locations.Name, (sum(case when Status = 'C'  then 1 else 0 end)/(select count(*)
from Candidates c where c.SpecifiedLocation=Locations.Id))*100
  as PercentCompleted
from Locations inner join Candidates ON Locations.Id = Candidates.SpecifiedLocation
inner join Courses on Candidates.Id = Courses.CandidateId
Group By Locations.Name