SQL Server使用已计算的总计查找百分比

时间:2018-05-29 10:24:23

标签: sql-server-2008

我有一个表格,其中包含每家公司的薪资值和总计。我想找到百分比而不确定如何?

istotal标志表示是否为总数; 0表示不是总计,1表示总计

create table work.temp
(
    empid int, 
    Salaryvalue float,
    istotal smallint
)

insert into work.temp 
values (1, 10.0, 0), (1, 20.0, 0), (1, 30.0, 0), (1, 60.0, 1)

这是预期的输出:

create table work.output
(
    empid int, 
    salaryvalue float,
    issubtotal smallint,
    percentage float
)

insert into work.output 
values (1, 10.0, 16.6),  --(10.0/60.0)*100
       (1, 20.0, 33.3),  --(20.0/60.0)*100
       (1, 30.0, 50.0),  --(30.0/60.0)*100
       (1, 60.0, 100.0)  --(60.0/60.0)*100

不太确定如何做到

谢谢先生

1 个答案:

答案 0 :(得分:1)

您可以使用窗口化聚合在每行上引用每个SalaryValue的{​​{1}}总计(empid对用于处理除以零的错误):

isnull nullif

输出:

declare @t table(empid int,SalaryValue float,istotal smallint);
insert into @t values(1, 10.0, 0), (1, 20.0, 0), (1, 30.0, 0), (1, 60.0, 1);

select empid
        ,SalaryValue
        ,istotal
        ,isnull(SalaryValue / nullif(sum(case when istotal = 1 then SalaryValue else 0 end) over (partition by empid),0),0) as Percentage
from @t;

或者,您可以将表格连接到自己,其中一个版本返回+-------+-------------+---------+-------------------+ | empid | SalaryValue | istotal | Percentage | +-------+-------------+---------+-------------------+ | 1 | 10 | 0 | 0.166666666666667 | | 1 | 20 | 0 | 0.333333333333333 | | 1 | 30 | 0 | 0.5 | | 1 | 60 | 1 | 1 | +-------+-------------+---------+-------------------+ ,另一个版本返回istotal = 1

istotal = 0

输出:

declare @t table(empid int,SalaryValue float,istotal smallint);
insert into @t values(1, 10.0, 0), (1, 20.0, 0), (1, 30.0, 0), (1, 60.0, 1);

with t as
(
    select empid
            ,SalaryValue
    from @t
    where istotal = 1
)
select s.empid
        ,s.SalaryValue
        ,t.SalaryValue as Total
        ,isnull(s.SalaryValue / nullif(t.SalaryValue,0),0) as Percentage
from @t as s
    left join t
        on s.empid = t.empid
where s.istotal = 0;