Sql server Group by返回0而不是负金额

Sql server Group by返回0而不是负金额,sql-server,group-by,Sql Server,Group By,运行此查询仅提供正金额,还将负金额替换为0。有没有办法解决这个问题?选择sum(金额小于0时为大小写,金额结束时为0),键入、ProductName、ProductCategory select sum(amount), Type, ProductName, ProductCategory from ProductAmount Group by Type, ProductName, ProductCategory 来自ProductAmount 按类型、产品名称、产品类别分组 或使用SQL

运行此查询仅提供正金额,还将负金额替换为0。有没有办法解决这个问题?

选择sum(金额小于0时为大小写,金额结束时为0),键入、ProductName、ProductCategory
select sum(amount), Type, ProductName, ProductCategory
from ProductAmount
Group by Type, ProductName, ProductCategory
来自ProductAmount 按类型、产品名称、产品类别分组
或使用SQL Server 2012+:

select sum(CASE WHEN amount < 0 THEN 0 ELSE amount END), Type, ProductName, ProductCategory
from ProductAmount
Group by Type, ProductName, ProductCategory
选择总和(IIF(金额<0,0,金额)),类型,产品名称,产品类别
来自ProductAmount
按类型、产品名称、产品类别分组

我解决了我的问题。有一些产品在购买后被退回。我没有意识到,该表记录了退货时的负金额和购买时的正金额。在我的例子中,当我使用SUM函数时,它将特定产品的数量相加,最终总数为0

这里的细节很少。我喜欢他们答案中的猜测。另一种选择可能是简单地添加where子句。“WHERE Amount>0”我解决了我的问题。有一些产品被退回,因此金额显示(例如)-1200,另外还有一个金额是在产品被退回之前购买的。所以当我使用求和函数时,它去掉了负数,取而代之的是0。
select sum(IIF(amount < 0, 0, amount)), Type, ProductName, ProductCategory
from ProductAmount
Group by Type, ProductName, ProductCategory