SQL Server:如何处理查询中被0除的情况
我有一个如下所示的查询,它正在获取百分比:
SELECT SUM(convert(decimal(3,2),
CASE WHEN Status_ID = 1 AND State_ID = 14 THEN 1 ELSE 0 END))/
SUM(convert(decimal(3,2),CASE WHEN State_ID = 14 THEN 1 ELSE 0 END)) * 100
FROM SomeTable
在正常情况下,这可能会返回类似 59.77803 的内容。但事实证明,在某些情况下,第二个 SUM(分母)可能为 0。有谁知道一种方法来解释这种情况并避免除以 0 异常?
我正在使用 SQL Server 2005。谢谢。
I have a query that looks like this, and which is getting a percentage:
SELECT SUM(convert(decimal(3,2),
CASE WHEN Status_ID = 1 AND State_ID = 14 THEN 1 ELSE 0 END))/
SUM(convert(decimal(3,2),CASE WHEN State_ID = 14 THEN 1 ELSE 0 END)) * 100
FROM SomeTable
This may return something like 59.77803 in a normal case. But it turns that there are (rightly) cases when the second SUM -- the denominator -- could be 0. Does anyone know of a way to account for this case and avoid a divide by 0 exception?
I'm using SQL Server 2005. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我可能会使用 NULL 来表示不可计算,但这取决于您在问题域中的意图(代码扩展以显示发生的情况):
表中没有行时的结果,因此分母为零 - 转换为NULL 因此整个表达式最终为 NULL。
该代码也可以稍微简化(可能是因为它已经是一个简化的玩具问题):
作为将许多不同的事物组合到一个查询中的示例:
I would probably use a NULL to represent uncalculatable, but it depends upon your intent in your problem domain (code expanded to show what's going on):
The result when there are no rows in the table so the denominator would be zero - gets converted to NULL so the whole expression ends up NULL.
That code can also be simplified a little (probably because it's already a simplified toy problem):
As an example of combining a number of different things into one query:
问问自己,当分母为 0 时,您想要返回什么结果?
然后据此相应地修复查询。
没有好的内置方法可以做到这一点。这是一个商业逻辑的事情。
ask yourself what's the result you want to return when the denominator is 0?
then based on that fix the query accordingly.
there's no good built-in way to do it. It's a business logic thing.
如果我没读错的话,这应该有效:
If I'm reading it right, this should work:
为了避免除以 0 异常,您可以使用接受分子、分母和默认值的函数,当分母为 0 时传递。并调用该函数进行除法。
To avoid divide by 0 exception you can use a function which accepts numerator,denominator and default value to pass when denominator is 0. And call that function to do division.
真正的问题是,当您尝试除以零时,“答案”应该是什么?我会将其设置为 NULL,因此请尝试这样的操作:
输出:
您的代码将是:
我不太明白 WHEN Status_ID = 1 AND State_ID = 14 THEN 1,但那是OP代码。
The real question is what should the "answer" be when you try to divide by zero? I'd make it
NULL
, so try something like this:OUTPUT:
your code would be:
I don't really understand the
WHEN Status_ID = 1 AND State_ID = 14 THEN 1
, but that is the OPs code.