代码之家  ›  专栏  ›  技术社区  ›  user2726975

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

  •  0
  • user2726975  · 技术社区  · 7 年前

    我有一个表,其中包含每个公司的工资值和总额。我想找到百分比,但不知道怎么做?

    这个 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 回复  |  直到 7 年前
        1
  •  1
  •   iamdave    7 年前

    您可以参考 SalaryValue 每个的合计 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;
    

    输出:

    +-------+-------------+-------+-------------------+
    | empid | SalaryValue | Total |    Percentage     |
    +-------+-------------+-------+-------------------+
    |     1 |          10 |    60 | 0.166666666666667 |
    |     1 |          20 |    60 | 0.333333333333333 |
    |     1 |          30 |    60 |               0.5 |
    +-------+-------------+-------+-------------------+