sql-server - 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
解决方案
你的尝试很接近。这应该根据提供的样本数据起作用。
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]
推荐阅读
- arrays - 如何将未知长度的字符放入数组中
- json - 如何使用 jq 消除包含来自 json 数据的冗余字段
- rxjs - Angular 9 和 rxjs - 在 postMessage 之后等待消息事件
- java - 获取 Activity 结果的 intExtra 时获取“预期 2 个参数,但找到 1 个”。不知道这里有什么问题
- jquery - 在 jQuery 中使用变量时出现控制台错误
- python-3.x - 如何使用漂亮的打印(python)将字典写入xml文件?
- c# - C# 绑定列表为我保存了 json 中的空值
- apache-spark - 无法安装 PySpark 模块错误未找到模块
- deno - Deno - 如何实现 404 页面
- python - 在不使用内置函数的情况下找到最长的连击