如何将 group-by T-SQL 语句中的所有负数清零
我有一个 T-SQL 查询,我希望将所有负数清零。
SELECT
p.productnumber,
v.[Description],
SUM(i.Quantity) as quantity
FROM ...
LEFT JOIN ...
LEFT JOIN ...
LEFT JOIN ...
GROUP BY productnumber, [Description]
基本上,如果总和由 5, 5, -1 组成,结果应该是 5+5+0=10,而不是 (5+5+(-1)=9。
我该怎么做?
I have a T-SQL query where I want all negative quantities to be zeroed out.
SELECT
p.productnumber,
v.[Description],
SUM(i.Quantity) as quantity
FROM ...
LEFT JOIN ...
LEFT JOIN ...
LEFT JOIN ...
GROUP BY productnumber, [Description]
Basically if the sum is made up of 5, 5, -1, the result should be 5+5+0=10, and not (5+5+(-1)=9.
How would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
CASE
语句或专有的
IIF
版本或更晦涩的版本
,或者在
WHERE
子句中完全排除这些行(如果它们是)不需要用于任何其他目的。在 Azure SQL 数据库中,您现在还可以使用
GREATEST
函数You could use a
CASE
statementOr the proprietary
IIF
versionOr a more obscure version
or just exclude these rows altogether in the
WHERE
clause if they are not needed for any other purpose.In Azure SQL Database you can now also use the
GREATEST
function for this直接过滤掉你不想要的...
just filter out the ones you don't want...
SUM(CASE WHEN i.Quantity < 0 THEN 0 ELSE i.Quantity END) 作为数量
SUM(CASE WHEN i.Quantity < 0 THEN 0 ELSE i.Quantity END) as quantity
我知道这个问题很久以前就已经得到了回答,但我认为值得一提的是,零层公式是:
在 SQL Server 中:
这在很多计算场景中都会出现。不确定这是否是在 TSQL 中执行此操作的最有效方法,或者像
CASE
这样的逻辑语句是否会更快。但这每次都 100% 有效。I know this has been answered a long time ago but I thinks its worth mentioning that the zero floor formula is:
In SQL Server its:
This comes up in a lot of computing scenarios. Not sure if it's the most efficient way to do it in TSQL or if logic statements like
CASE
would be faster. But this works 100% of the time every time.