我有4列的查询
我想为每个董事会的总奖金百分比添加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
到目前为止,我已经学会了如何将查询组合在一起,但我想学习如何使用上面的操作。
答案 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;