添加累计/运行总计

时间:2020-02-13 15:30:45

标签: sql sql-server tsql group-by window-functions

我正在尝试对sql上的计算列进行总计(未成功)。

我的原始代码:

select t.codigo, t.nome, t.total  
from(
select codigo, nome,  SUM(CASE When ANO = 2018 Then VLCOMPRA Else 0 End ) as total
from clientes
left join ACUMTERC on ACUMTERC.TPTERC = 2 and TPOPER = 2 AND ACUMTERC.TERCEIRO = CLIENTES.CODIGO
group by codigo, nome) as t   
ORDER BY total DESC

我尝试过的事情:

select t.codigo, t.nome, t.total, SUM(t.total) OVER(PARTITION BY t.codigo ORDER BY t.codigo) RunningTotal    
from( select codigo, nome, SUM(CASE When ANO = 2018 Then VLCOMPRA Else 0 End ) as total from clientes left join ACUMTERC on ACUMTERC.TPTERC = 2 and TPOPER = 2 AND ACUMTERC.TERCEIRO = CLIENTES.CODIGO group by codigo, nome) as t   
ORDER BY total DESC

我的结果:

codigo | nome  | total | Running total
-------+-------+-------+---------------
000001 | name1 |   300 !   300
000003 | name3 |   200 |   200
000002 | name2 |   100 |   100

我需要什么:

codigo | nome  | total | Running total
-------+-------+-------+---------------
000001 | name1 |   300 !   300
000003 | name3 |   200 |   500
000002 | name2 |   100 |   600

有帮助吗? 谢谢。

2 个答案:

答案 0 :(得分:1)

我强烈怀疑您的查询可以简化:

  • 首先,我不明白为什么需要进行条件求和:您可以只过滤join
  • 根本不需要子查询

在需要时,您可以创建一个窗口sum()

我也强烈建议在每列的前面加上它所属的表的前缀:这使查询对数据结构毫无疑问;我做了一些假设,您可能要检查一下(我也使用表别名来缩短查询)。

考虑:

select 
    c.codigo, 
    c.nome,  
    coalesce(sum(a.vlcompra), 0) as total,
    sum(coalesce(sum(a.vlcompra), 0)) 
        over(order by coalesce(sum(a.vlcompra), 0) desc) running_total
from clientes c
left join acumterc a 
    on  a.tpterc = 2 
    and a.tpoper = 2 
    and a.terceiro = c.codigo
    and a.ano = 2018
group by c.codigo, c.nome

答案 1 :(得分:0)

您可以使用不受限制的前行和当前行之间的行来实现此目的:

select t.codigo, t.nome, t.total, 
SUM(t.total) OVER(ORDER BY t.codigo ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) RunningTotal

from( select codigo, nome, SUM(CASE When ANO = 2018 Then VLCOMPRA Else 0 End ) as total from clientes left join ACUMTERC on ACUMTERC.TPTERC = 2 and TPOPER = 2 AND ACUMTERC.TERCEIRO = CLIENTES.CODIGO group by codigo, nome) as t

    ORDER BY total DESC

数据示例:

 with tbl as
(
select '000001' as codigo , 'name1' as nome,   300 as total,  300 as Running_total
union select '000003' , 'name3' ,   200 ,   200
union select '000002' , 'name2' ,   100 ,   100
)

select t.codigo, t.nome, t.total, 
SUM(t.total) OVER(ORDER BY t.codigo asc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) RunningTotal

from tbl as t
ORDER BY codigo asc
  with tbl as
(
select '000001' as codigo , 'name1' as nome,   300 as total,  300 as Running_total
union select '000003' , 'name3' ,   200 ,   200
union select '000002' , 'name2' ,   100 ,   100
)

select t.codigo, t.nome, t.total, 
SUM(t.total) OVER(ORDER BY t.codigo asc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) RunningTotal

from tbl as t
ORDER BY codigo asc

输出:

codigo  nome    total   RunningTotal
000001  name1     300   300
000002  name2     100   400
000003  name3     200   600