计算多行并在SQL Server

时间:2017-04-14 20:39:46

标签: sql-server

我想更新表以总结一些行(不是所有行)并更新名为“Total”的行。

然后基于Total,我将对其他一些行进行一些计算,并将结果设置为名为Sub的行。

表I有类似

的内容
        id  C1 C2 C3 C4 C5
R1      1   1  12  2  3  5
R2      2   3  3  41  4  3
R3      3   5  3  32  2  6
Total   4   = R1 + R2 + R3
R4      5   1  2  4  13  4 
R5      6   3  5  1   3  4
Sub     7   = Total - R4 - R5

基于上面的计算,我应该得到一个像这样的表

      id   C1 C2 C3 C4 C5 
R1    1    1  12  2  3  5
R2    2    3  3  41  4  3
R3    3    5  3  32  2  6
Total 4    9  18 75  9  14
R4    5    1  2  4  13  4 
R5    6    3  5  1   3  4
Sub   7    5  11 70 -7  6

这也是临时表。

我尝试累积但似乎没有执行此工作。

update #tempreport
set C1 = sum(C1),
    C2 = sum(C2),
    C3 = sum(C3), 
    C4 = sum(C4), 
    C5 = sum(C5)
where id = 4 and id between 1 and 3

但是我收到了一个错误:

  

聚合可能不会出现在UPDATE语句的集合列表中。

我真的被困了,我觉得第二个要求更具挑战性,我不知道如何在SQL中执行类似的操作。任何想法都会有所帮助。

谢谢!

2 个答案:

答案 0 :(得分:0)

得到了问题第一部分的答案。 归功于此link

使用子查询。在这种情况下,我会

update #tempreport
set C1 = tbl.C1, 
    C2 = tbl.C2, 
    C3 = tbl.C3, 
    C4 = tbl.C4,
    C5 = tbl.C5
from (
     select id, sum(C1) as C1, sum(C2) as C2, sum(C3) as C3...
     from #tempreport
     where id between 1 and 3
) as tbl
where id=4 

答案 1 :(得分:0)

-- Step 1: update the "SUM" row (in the example it has id = 4)
update #tempreport set C1 = sum1, C2 = sum2, C3 = sum3, C4 = sum4, C5 = sum5
from (
    select sum(C1) as sum1, sum(C2) as sum2, sum(C3) as sum3, 
           sum(C4) as sum4, sum(C5) as sum5
    from #tempreport
    where id between 1 and 3
) sums
where #tempreport.id = 4
;

-- Step 2: update the "DIFF" row (id = 7):
update #tempreport set #tempreport.C1 = x.C1-sum1, #tempreport.C2 = x.C2-sum2,    
                       #tempreport.C3 = x.C3-sum3, #tempreport.C4 = x.C4-sum4, 
                       #tempreport.C5 = x.C5-sum5
from (
    select sum(C1) as sum1, sum(C2) as sum2, sum(C3) as sum3, 
           sum(C4) as sum4, sum(C5) as sum5
    from #tempreport
    where id between 5 and 6
) subtr, (select * from #tempreport where id = 4) x
where #tempreport.id = 7