获取前三行:with子句

时间:2015-12-31 19:24:06

标签: oracle plsql

我有以下查询:

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返回的前三行,怎么做?

2 个答案:

答案 0 :(得分: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
)  

答案 1 :(得分:0)

如果你有oracle 12c,你可以先使用fetch

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