Oracle SQL - 查找数据集的最小值,但在 MIN 计算中排除某个值
Oracle 版本:10g
我正在尝试使用 MIN
函数来查找数据集的最小值/最小值。我正在执行 MIN
的列是 VARCHAR2
列。此列将包含数字值或“--”值(表示该值不适用)。
对列执行 MIN()
函数时,始终返回“--”。
我想找到一种方法来排除 MIN 语句中计算的“--”。我无法在语句中使用 WHERE 子句来过滤掉带有“--”的列,因为这会排除有效数据。
注意:这是一个巨大的遗留查询(500 多行),因此重写这个巨大的查询实际上并不是一个选择。
Oracle version : 10g
I'm trying to use the MIN
function to find the minimum/lowest value of a dataset. The column I'm performing MIN
on is a VARCHAR2
column. This column will either contain a numeric value, or a value of '--' which represents that the value is not applicable.
When performing the MIN()
function on the column, the '--' is always returned.
I want to find a way to exclude the '--' from being calculated in the MIN statement. I can't use the WHERE clause in the statement to filter out columns with a '--' because that would exclude valid data.
Note: This is a huge legacy query (500+ lines) so re-writing this massive query is not really an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MIN(CASE WHEN ColX = '--' THEN NULL ELSE ColX END)
这在 SQL Server 中有效,我认为也可能在 Oracle 上工作。
附带说明一下,永远不要在字符串字段中存储数字数据。
从空间角度来看,这是低效的,并且在进行不等式比较时,您会得到一些奇怪的结果。
如果您的表中有这些行:
MAX
值为1
,MIN
值为009
MIN(CASE WHEN ColX = '--' THEN NULL ELSE ColX END)
This is valid in SQL Server and I think will probably work on Oracle as well.
As a side note, never ever store numeric data in string fields.
It's inefficient from a space perspective and you will get some weird results when doing inequality comparisons.
If you have these rows in your table:
The
MAX
value will be1
and theMIN
value will be009
实际上,您只是希望聚合函数避免该值。聚合会跳过空值,因此将有问题的值转换为空值:
此外,正如 @JNK 指出的那样,将数字存储为字符串充满了危险。例如,除非您的数字全部填充到相同的长度,否则
min
可能会给出错误的结果:作为字符串,“1000”小于“2”。您可以使用float
或int
函数将字符串转换为实际数字,但如果其中有任何其他非数字字符,那么 SQL 将抛出错误。Really you just want the aggregate function to avoid this value. Aggregates skip nulls, so transform the value in question into a null:
Also, as @JNK points out, storing numbers as strings is fraught with peril. For instance, unless your numbers are all padded to the same length,
min
will probably give you the wrong result: as strings, '1000' is less than '2'. You can use thefloat
orint
functions to convert your strings to actual numbers, but if you have any other non-numeric characters in there then the SQL will throw an error.