SQL:完成百分比

问题描述 投票:2回答:2

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

课程表具有Status ='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查询实现吗?

sql
2个回答
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;

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
© www.soinside.com 2019 - 2024. All rights reserved.