首页 > 解决方案 > SQL Server你如何得到一个列的总和,如果它小于0,则从另一列添加,否则添加该列?

问题描述

select 
  sum(case when Apt.productionValue != '-1.0' then Apt.subTotal 
    else Apt.productionValue end) as ProductionValue,Apt.date
from Appointment Apt
group by Apt.date 
order by Apt.date asc
预约ID 产值 小计 日期
1 -1 10 2021-09-02
2 10 0 2021-09-02
3 -1 20 2021-09-01
4 -1 20 2021-09-01
5 5 0 2021-09-01

我试图仅在生产值超过 0 时才获得总和,否则为该行添加小计。

最终目标是 2021-09-02 和 2021-09-01 的总和仍然是 20 和 45

标签: sql-server

解决方案


你的尝试很接近。这应该根据提供的样本数据起作用。

select Apt.[Date]
    , sum(case when Apt.ProductionValue < 0 then Apt.SubTotal else Apt.ProductionValue end)
from Appointment  Apt
group by Apt.[Date]
order by Apt.[Date]

推荐阅读