如何排除从查询结果中的最新的空场?
问题描述:
我想设计一个查询,以找出是否有至少一只猫(SELECT COUNT(*),其中的rownum = 1)尚未签出。如何排除从查询结果中的最新的空场?
一个奇怪的条件是,结果应排除如果没有签出最新的猫,这样:
TABLE schedule
-------------------------------------
| type | checkin | checkout
-------------------------------------
| cat | 20:10 | (null)
| dog | 19:35 | (null)
| dog | 19:35 | (null)
| cat | 15:31 | (null) ----> exclude this cat in this scenario
| dog | 12:47 | 13:17
| dog | 10:12 | 12:45
| cat | 08:27 | 11:36
应该返回1,第一条记录
| cat | 20:10 | (null)
我类似于创建查询
select * from schedule where type = 'cat' and checkout is null order by checkin desc
但是,此查询不能解析排除。我可以肯定处理它像Java服务层,但只是想知道的任何解决方案可以在查询设计与良好的性能当在表大量数据的(签入和签出被编入索引,但不会打字)
答
这个怎么样?
Select *
From schedule
Where type='cat' and checkin=(select max(checkin) from schedule where type='cat' and checkout is null);
答
假设checkin
和checkout
数据类型为字符串(它不应该是,它应该是DATE),to_char(checkin, 'hh24:mi')
将创建正确的数据类型,日期的值,假定当前的第一天月份作为“日期”部分。这对你来说无关紧要,因为大概所有的时间都来自同一天。如果实际checkin/out
处于正确的DATE数据类型中,则不需要在order by
(两处)中调用to_date()
。
我忽略了输出中的checkout
列,因为您只查找该列中的行数为null
,因此将其包括在内不会提供任何信息。我已经离开了type
为好,但也许你会想有这个在以后某个时间猫和狗...
with
schedule(type, checkin, checkout) as (
select 'cat', '20:10', null from dual union all
select 'dog', '19:35', null from dual union all
select 'dog', '19:35', null from dual union all
select 'cat', '15:31', null from dual union all
select 'dog', '12:47', '13:17' from dual union all
select 'dog', '10:12', '12:45' from dual union all
select 'cat', '08:27', '11:36' from dual
)
-- end of test data; actual solution (SQL query) begins below this line
select type, checkin
from (select type, checkin,
row_number() over (order by to_date(checkin, 'hh24:mi')) as rn
from schedule
where type = 'cat' and checkout is null
)
where rn > 1
order by to_date(checkin, 'hh24:mi') -- ORDER BY is optional
;
TYPE CHECKIN
---- -------
cat 20:10
哪些数据类型是'checkin'和'checkout'?它看起来像字符串(也许'varchar2'),这将导致非常差的执行效率。如果确实如此,并且您需要良好性能,则应将其更改为适当的数据类型(DATE)。那么,如果两只没有被检出的猫被绑定为“最近的检查”,会发生什么? – mathguy