2016-11-06 73 views
0

我想設計一個查詢,以找出是否有至少一隻貓(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服務層,但只是想知道的任何解決方案可以在查詢設計與良好的性能當在表大量數據的(簽入和簽出被編入索引,但不會打字)

+0

哪些數據類型是'checkin'和'checkout'?它看起來像字符串(也許'varchar2'),這將導致非常差的執行效率。如果確實如此,並且您需要良好性能,則應將其更改爲適當的數據類型(DATE)。那麼,如果兩隻沒有被檢出的貓被綁定爲「最近的檢查」,會發生什麼? – mathguy

回答

0

這個怎麼樣?

Select * 
From schedule 
Where type='cat' and checkin=(select max(checkin) from schedule where type='cat' and checkout is null); 
0

假設checkincheckout數據類型爲字符串(它不應該是,它應該是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