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
tbody> <<tr>245
apppointmentd产值小计日期
11102021-09-02
1002021-09-02
31202021-09-01
1202021-09-01
502021-09-01

你差一点就成功了。这应该基于所提供的样例数据。

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]

您可以在子查询中选择期望的列,如:

select Date, SUM(ProductionValue) as ProductionValue
from (
select
Date,
case when ProductionValue > 0
then ProductionValue 
else SubTotal end
as ProductionValue
from Appointment
) as d
group by Date
order by Date

相关内容

最新更新