如何计算SQL Server 2008中的百分比

时间:2016-05-16 11:06:05

标签: sql sql-server

我有4列的查询

  • 首长,
  • t1参加课程的董事会员工人数
  • t2,了解董事会的课程数量
  • t3,每个董事会花费的总奖金

我想为每个董事会的总奖金百分比添加t4

公式为(t3 / total sum of t3) * 100

这是查询:

with cte1 as
(
    select   
        vwemployee.directorateName, 
        count(distinct vwemployeeCourse.employeeId) as t1 
    from 
        vwemployee, vwemployeeCourse 
    where  
        vwemployee.directorateName = vwemployeeCourse.directorateName 
    group by    
       vwemployee.directorateName
), cte2 as
(
    select 
        vwemployee.directorateName, 
        count(vwemployee.directorateName) as t2 
    from 
        vwemployee, employeeCourse
    where 
        vwemployee.Id = employeeCourse.employeeId 
    group by 
        vwemployee.directorateName
), cte3 as
(
    select 
        vwemployeeCourse.directorateName, 
        sum(vwCourse.cost) as t3
    from 
        vwemployeeCourse, vwCourse
    where 
        vwemployeeCourse.courseId = vwCourse.Id
    group by
        vwemployeeCourse.directorateName 
)
select 
    cte1.directorateName, cte1.t1, cte2.t2, cte3.t3
from
    cte1 
inner join 
    cte2 on cte1.directorateName = cte2.directorateName
inner join 
    cte3 on cte2.directorateName = cte3.directorateName

到目前为止,我已经学会了如何将查询组合在一起,但我想学习如何使用上面的操作。

1 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

with . . .
select cte1.directorateName, cte1.t1, cte2.t2, cte3.t3,
       cte3.t3 / sum(cte3.t3) over ()
from cte1 inner join
     cte2 
     on cte1.directorateName = cte2.directorateName inner join
     cte3
     on cte2.directorateName = cte3.directorateName;

如果t3是整数,则需要将其转换为带小数点的数字(SQL Server执行整数除法):

with . . .
select cte1.directorateName, cte1.t1, cte2.t2, cte3.t3,
       cte3.t3*100.0 / sum(cte3.t3) over ()
from cte1 inner join
     cte2 
     on cte1.directorateName = cte2.directorateName inner join
     cte3
     on cte2.directorateName = cte3.directorateName;