我有一张包含三列的 table (tipo,ok,ko)。我正在尝试找到一种方法,根据使用 T-sql 的条件对值进行求和,例如下表
对于每一行,我试图将 Ko + ok 的总和作为总计,但对于总和行,我想将相互总计,因此对于空值,我想将所有 ko 的总和与相互 ok 相加,因此在最后,我需要为所有 4 个空值设置 7,957,因此 ko1(15) + ko2(82) +ko3(130) +ko4(65) +mutual ok (7665) 因此所需的结果应如下表所示,
这是我正在使用的代码,但它只是对第一种情况的两列求和,我需要修改它以获得第二种情况并在第二个表上获得所需的结果
select TIPO, KO, OK,
sum(case when tipo in('act-act','scopertura','Silver100%') then (ko+ok)
else null
end ) as totale
From table
group by tipo , ok , ko
最佳答案
您可以使用窗口函数而不是子查询来计算总体计数 - 从而避免额外的(且不必要的)表扫描:
select t.*,
case
when tipo in ('act-act','scopertura','Silver100%')
then ko + ok
else ok + sum(case when tipo not in ('act-act','scopertura','Silver100%') then ko else 0 end) over()
end totale
from mytable t
sum(...) over()
表达式对整个表中给定 tipo
的 ko
进行窗口求和.
如果您不想重复自己,可以先在子查询中的 tipo
上设置一个标志,然后在外部查询中使用它:
select t.*,
case
when flag_tipo = 1
then ko + ok
else ok + sum(case when flag_tipo = 0 then ko else 0 end) over()
end totale
from (
select t.*,
case when tipo in ('act-act','scopertura','Silver100%') then 1 else 0 end as tipo_flag
from mytable t
) t
关于sql - 有条件求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75768890/