2015-12-31 117 views
-1

我有以下查詢:獲得前三行:與第

with TEMPRESULT AS 
(
    select CONTACTS.line_id , count(*) totalcount 
    from CONTACTS 
    where (((E_DATE-S_DATE)*24*60*60)<=60 and to_char(S_DATE,'YYYY-MM-DD')='2015-12-12') 
    group by CONTACTS.line_id 
    order by totalcount DESC 
) 

我想TEMPRESULT只持有由select返回的前三排,那怎麼辦?

回答

1

您可以指定rownum條件:

with TEMPRESULT AS 
(
    select * from 
    (
     select CONTACTS.line_id , count(*) totalcount 
     from CONTACTS 
     where (((E_DATE-S_DATE)*24*60*60)<=60 and to_char(S_DATE,'YYYY-MM-DD')='2015-12-12') 
     group by CONTACTS.line_id 
     order by totalcount DESC 
    ) x 
    where rownum < 3 
) 
0

,如果你有甲骨文12C可以使用取第一

WITH TEMPRESULT AS 
    (SELECT CONTACTS.line_id , 
    COUNT(*) totalcount 
    FROM CONTACTS 
    WHERE (((E_DATE-S_DATE)*24*60*60)<=60 
    AND TO_CHAR(S_DATE,'YYYY-MM-DD') ='2015-12-12') 
    GROUP BY CONTACTS.line_id 
    ORDER BY 2 DESC 
    FETCH FIRST 3 rows only 
) 
SELECT * FROM tempresult