昨天写一个需求需要的sql遇到一些问题,在此记录一下,需要查询时间段内所有HGB检验结果大于等于110的人次的总数,本身想的是将非数字的数据过滤掉当做一个子查询的结果集
select *
from LISDATA_REPORT_DETAIL t
where t.item_id = 'HGB'
and trunc(t.reslt_time) >= to_date('2020-01-01', 'yyyy-MM-dd')
and ltrim(RESULT, '1234567890.') is null
查询结果如下图:
查询的结果集里面确实没有非数字的数据,但是当我加了大于110的条件时,报了无效数字的错误,该语句如下:
select *
from (select *
from LISDATA_REPORT_DETAIL t
where t.item_id = 'HGB'
and trunc(t.reslt_time) >= to_date('2020-01-01', 'yyyy-MM-dd')
and ltrim(RESULT, '1234567890.') is null) a
where to_number(a.result) > 110
然后按照同事提供的一个方法试了一下
select *
from (select *
from (select *
from (select *
from LISDATA_REPORT_DETAIL t
where t.item_id = 'HGB'
and trunc(t.reslt_time) >=
to_date('2020-01-01', 'yyyy-MM-dd')
--and ltrim(RESULT, '1234567890.') is null
) a)
where rownum > 0) b
--where to_number(b.result) >= 110
此语句在查询时生成的结果如下
此时,result结果中有非数字的内容,现在要求去掉非数字的内容,将注释解开如下:
select *
from (select *
from (select *
from (select *
from LISDATA_REPORT_DETAIL t
where t.item_id = 'HGB'
and trunc(t.reslt_time) >=
to_date('2020-01-01', 'yyyy-MM-dd')
and ltrim(RESULT, '1234567890.') is null) a)
where rownum > 0) b
where to_number(b.result) >= 110
执行后结果如下,加上rownum限制可以正常查询出需要的数据
问了下同事,说是可能是Oracle底层中的问题,结果集中过滤掉了非数字的但实际还是存在,只是将那些数据隐藏起来,伪列的序号小于0,所以大于rownum0才会将这些真正过滤掉(只是猜测),具体怎么回事有大佬知道的话欢迎指正